Why can't add element in a upper bound generics List?

generics, java

Solution

`List<? extends Number>` does not mean "a list that can hold all objects of subclasses of `Number`", it means "a list parameterized to one concrete class that extends `Number`". It's not the contents of the list itself you are defining, it's what the parameterized type of the actual list-object assigned to the variable can be (boy, this is harder to explain than it is to understand :) )

So, you can do:

List<? extends Number> l = new ArrayList<Integer>();
List<? extends Number> l = new ArrayList<Double>();

If you want a list that is able to hold any object of class Number or its subclasses, just do this:

List<Number> l = new ArrayList<>();

l.add(new Integer(33));
l.add(new Double(33.3d));

(The boxing of the values inserted is unnecessary, but there for clarity..)

Problem

I have a list with upper bound generics. ``` List<? extends Number> l = new ArrayList<>(); l.add(new Integer(3)); //ERROR l.add(new Double(3.3)); // ERROR ``` I don't understand the problem, because Integer and Double extend Number.

Original source