What's the difference between <?> and <? extends Object> in Java Generics?
Solution 1:
<?>
and <? extends Object>
are synonymous, as you'd expect.
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
.)
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
)
Solution 2:
Although <?>
is supposed to be a shortcut for <? extend object>
, there is a tiny difference between the two.
<?>
is reifiable while <? extend object>
is not. The reason they did this is to make it easier to distinguish reifiable type. Anything that looks like <? extends something>
,<T>
,<Integer>
are nonreifiable.
For example, this code would work
List aList = new ArrayList<>();
boolean instanceTest = aList instanceof List<?>;
but this gives an error
List aList = new ArrayList<>();
boolean instancetest = aList instanceof List<? extends Object>;
for more info read Java generics and collections by Maurice Naftalin