Difficulty Understanding Wildcards in Java

It's hard for me to understand wildcards in Java generics. In particular, I have the following questions:

  • If we have a LinkedList<?> , Why can't we add an Object to it? I understand that he does not know the type of the list, but will Object add to the list if we consider it in any situation?

  • As in the previous question, if we have a LinkedList<? extends Number> LinkedList<? extends Number> why can't we add a Number ?

  • Finally, if we have a LinkedList<? super Number> LinkedList<? super Number> , why can we add a Integer to the list, can't we add things that are the superclass of Number?

I suppose I'm trying to understand how group templates in general work, I read Oracle tutorials on them and several other things, but I don’t understand why they work, I suppose.

+6
source share
1 answer

You are confusing objects and types.
Unlike simple general parameters, wildcards describe the type of general parameter.
A List<? super Number> List<? super Number> not a list of superclasses of Number ; this is a list of an unknown type, where this type is the superclass of a number.

A LinkedList<?> Could be a LinkedList<Car> .
Since Object not a Car , you cannot add an Object to it.

In fact, since you know nothing about what type the list contains, you cannot add anything to it. (except null )

Similarly, LinkedList<? extends Number> LinkedList<? extends Number> may be a List<Long> , so you cannot add Integer to it. (since Integer not Long )

On the other hand, List<? super Number> List<? super Number> definitely allowed to contain Number or any derived class, as it can only be a list of one of the Number superclasses (e.g. List<Object> )

+5
source

All Articles