What is the difference between <?> And <? extends Object> in Java Generics?

I have seen the wildcard used before to denote any object, but recently seen usage:

<? extends Object> 

Since all objects extend Object, are these two synonyms?

+65
java syntax generics
Nov 08 '11 at 18:33
source share
3 answers

<?> and <? extends Object> <? extends Object> are synonyms, as you would expect, but there are a few cases with generics where the extends Object is actually not redundant. For example, <T extends Object & Foo> will cause T become Object under erasure, whereas with <T extends Foo> it will become Foo when erased. (This may make a difference if you are trying to maintain compatibility with the API until the generation that Object used.)

(Source: http://download.oracle.com/javase/tutorial/extra/generics/convert.html , this explains why the JDK class java.util.Collections has a method with this signature:

 public static <T extends Object & Comparable<? super T>> T max(Collection<? extends T> coll) 

.)

+75
Nov 08 '11 at 18:41
source share

Although <?> Should be a shortcut to <? extend object> <? extend object> , there is a slight difference between the two. <?> can be reused, but <? extend object> <? extend object> - no. The reason they did this is to make it easier to recognize a repeating type. Anything that looks like <? extends something> <? extends something> , <T> , <Integer> , is not valid.

For example, this code will work

 List aList = new ArrayList<>(); boolean instanceTest = aList instanceof List<?>; 

but it gives an error

 List aList = new ArrayList<>(); boolean instancetest = aList instanceof List<? extends Object>; 

read Java generics and collections from Maurice Naftalin for more information

+17
Jan 06 '16 at 3:40
source share

<?> is short for <? extends Object> <? extends Object> . You can read the general link below for more details.




 <?> 

"?" denotes any unknown type, it can represent any type in the code for. Use this template if you are not sure about the type.

 ArrayList<?> unknownList = new ArrayList<Number>(); //can accept of type Number unknownList = new ArrayList<Float>(); //Float is of type Number 

Note. <?> means anythings. Thus, it can take a type that is not inherited from the Object class.

 <? extends Object> 

<? extends Object> <? extends Object> means that you can pass an object or subclass that extends the Object class.

 ArrayList<? extends Number> numberList = new ArrayList<Number>(); //Number of subclass numberList = new ArrayList<Integer>(); //Integer extends Number numberList = new ArrayList<Float>(); // Float extends Number 



enter image description here

T - used to indicate type E - used to indicate element K - keys
V - values
N - for numbers
Link:

enter image description here

+2
Jul 05 '17 at 14:23
source share



All Articles