What's the difference between <?> and <? extends Object> in Java Generics?

orbfish picture orbfish · Nov 8, 2011 · Viewed 44.9k times · Source

I've seen the wildcard used before to mean any object - but recently saw a use of:

<? extends Object>

Since all objects extend Object, are these two usages synonymous?

Answer

ruakh picture ruakh · Nov 8, 2011

<?> 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
)