Lists are not covariant. If you use ? extends Number
then you can only read from the list, you can't write to it. Why not?
m1.add(new Object());
It should be obvious why this doesn't work. The list is supposed to contain Number
s and an Object
is not a Number
.
ml.add(new Integer(1));
This one's not so obvious. Imagine that you had a different instantiation of m1
:
List<? extends Number> ml = new Vector<Double>();
ml.add(new Integer(1));
Now m1
is a vector of doubles. Adding an integer to this list would be illegal. The compiler doesn't in general know what the concrete type of ? extends Number
is. To be conservative, it disallows calling the add
method entirely. You can iterate over the list and read what's in it, and you can delete items from it, but you can't add new items to it.
Or to put it another way, for List<E>
you can call methods that return E
but you can't call ones that take E
as a parameter.