Java泛型T vs Object [英] Java generics T vs Object
问题描述
我想知道以下两种方法声明有什么不同:
public Object doSomething(Object obj){。 ...}
public< T> T doSomething(T t){...}
您可以/可以做些什么一个而不是另一个?我在这个网站的其他地方找不到这个问题。 解决方案
在 但是有了上下文 - 如果你有一个泛型类: 然后: 与对象相同的代码 两个优点:$ b I was wondering what is the difference between the following two method declarations: Is there something you can/would do with one but not the other? I could not find this question elsewhere on this site. Isolated from context - no difference. On both But with context - if you have a generic class: Then: Same code with object Two advantages: 这篇关于Java泛型T vs Object的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋! t
和 obj
上,您只能调用 Object $ c $
MyClass的<富> my = new MyClass< Foo>();
Foo foo = new Foo();
Foo newFoo = my.doSomething(foo);
Foo newFoo =(Foo)my.doSomething(foo);
$ b $ ul
Object
版本,您不能确定该方法总是返回 Foo
。如果它返回 Bar
,那么在运行时您将有一个 ClassCastException
。
public Object doSomething(Object obj) {....}
public <T> T doSomething(T t) {....}
t
and obj
you can invoke only the methods of Object
.MyClass<Foo> my = new MyClass<Foo>();
Foo foo = new Foo();
Foo newFoo = my.doSomething(foo);
Foo newFoo = (Foo) my.doSomething(foo);
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.