Java 泛型 T 与对象 [英] Java generics T vs Object

查看:82
本文介绍了Java 泛型 T 与对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想知道以下两个方法声明有什么区别:

I was wondering what is the difference between the following two method declarations:

public Object doSomething(Object obj) {....}

public <T> T doSomething(T t) {....}

有什么你可以/愿意用一个而不是另一个做的吗?我在本网站的其他地方找不到这个问题.

Is there something you can/would do with one but not the other? I could not find this question elsewhere on this site.

推荐答案

与上下文隔离 - 没有区别.在 tobj 上你只能调用 Object 的方法.

Isolated from context - no difference. On both t and obj you can invoke only the methods of Object.

但是有上下文 - 如果你有一个泛型类:

But with context - if you have a generic class:

MyClass<Foo> my = new MyClass<Foo>();
Foo foo = new Foo();

那么:

Foo newFoo = my.doSomething(foo);

与对象相同的代码

Foo newFoo = (Foo) my.doSomething(foo);

两大优势:

  • 不需要强制转换(编译器对你隐藏了这个)
  • 编译时安全有效.如果使用 Object 版本,您将无法确定该方法总是返回 Foo.如果它返回 Bar,您将在运行时遇到 ClassCastException.
  • no need of casting (the compiler hides this from you)
  • compile time safety that works. If the Object version is used, you won't be sure that the method always returns Foo. If it returns Bar, you'll have a ClassCastException, at runtime.

这篇关于Java 泛型 T 与对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆