Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Difficulty Understanding Wildcards in Java

I'm having difficulty understanding wildcards in Java generics. Specifically I have the following questions:

  1. If we have a LinkedList<?>, why can we not add an Object to it? I understand that it doesn't know the type of the list, but wouldn't adding an Object to the list have us covered in any situation?

  2. Similar to the question above, if we have LinkedList<? extends Number>, why can we not add a Number to it?

  3. Finally, if we have LinkedList<? super Number>, why can we add an Integer to the list, shouldn't we only be able to add things that are a superclass of Number?

I guess I'm trying to understand how wildcards work in general, I've read the Oracle tutorials on them, and a few other things, but I don't understand why they work I suppose.

like image 730
hcaulfield57 Avatar asked Mar 12 '14 17:03

hcaulfield57


1 Answers

You're confusing objects and types.
Unlike simple generic parameters, wildcards describe the type of the generic parameter.
A List<? super Number> isn't a list of superclasses of Number; it's a list of some unknown type, where that type is a superclass of number.

A LinkedList<?> might be a LinkedList<Car>.
Since an Object is not a Car, you can't add an Object to it.

In fact, since you don't know anything about what type the list contains, you can't add anything to it. (except null)

Similarly, a LinkedList<? extends Number> might be a List<Long>, so you can't add an Integer to it. (since an Integer is not a Long)

On the other hand, a List<? super Number> is definitely allowed to contain Number or any derived class, since it can only be a list of one of Number's superclasses (eg, List<Object>)

like image 157
SLaks Avatar answered Oct 06 '22 17:10

SLaks