<?>之间的区别是什么?和<?扩展对象>在Java泛型?
我看过以前用过的通配符,意思是任何对象 - 但最近看到了使用:
I've seen the wildcard used before to mean any object - but recently saw a use of:
<? extends Object>
由于所有对象都是扩展Object的,这两个用法是否同义?
Since all objects extend Object, are these two usages synonymous?
<?>
和 是同义词,正如你所期望的那样,但是有一些泛型的情况,其中
extends Object
实际上并不是多余的。例如,< T extends Object& Foo>
会导致 T
在擦除时变为 Object
,而使用< T扩展Foo>
它会在擦除时变成 Foo
。 (如果您试图保留与使用 Object $ c>的预泛型API的兼容性,这可能很重要。)
<?>
and <? extends Object>
are synonymous, as you'd expect, but there are a few cases with generics where extends Object
is not actually redundant. For example, <T extends Object & Foo>
will cause T
to become Object
under erasure, whereas with <T extends Foo>
it will become Foo
under erasure. (This can matter if you're trying to retain compatibility with a pre-generics API that used Object
.)
(来源: http://download.oracle.com/javase/tutorial/extra/generics/ convert.html ;它解释了为什么JDK的 java.util.Collections
类有一个带有这个签名的方法:
(Source: http://download.oracle.com/javase/tutorial/extra/generics/convert.html; it explains why the JDK's java.util.Collections
class has a method with this signature:
public static <T extends Object & Comparable<? super T>> T max(Collection<? extends T> coll)
。)