Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 706
orbfish Avatar asked Nov 08 '11 18:11

orbfish


People also ask

What does <? Extends mean in Java?

The extends keyword extends a class (indicates that a class is inherited from another class). In Java, it is possible to inherit attributes and methods from one class to another. We group the "inheritance concept" into two categories: subclass (child) - the class that inherits from another class.

What is the difference between list <? Super T and list <? Extends T?

super is a lower bound, and extends is an upper bound.

What does <? Super E mean?

super E> , it means "something in the super direction" as opposed to something in the extends direction.

What is difference between extends and super?

Producer – If you want to only retrieve the elements from a generic collection, use extends . Consumer – If you want to only put elements into a generic collection, use super . If you do both retrieve and put operations with the same collection, you shouldn't use either extends or super .


1 Answers

<?> 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 ) 
like image 76
ruakh Avatar answered Oct 05 '22 11:10

ruakh