You cannot add anything except null
to a List
bounded by a wildcard because you never know the underlying type.
List<? extends Integer> lst= new ArrayList<Integer>();
lst.add(5); // Compile error
lst.get(5); // 5 is just the index
You can however get an element because you know it must be an Integer
(in this case).
It's hard to explain with Integer
because it's a class that cannot be extended. But take this
public class Foo {}
public class Bar extends Foo {}
public class Zoop extends Foo {}
What could you add to
List<? extends Foo> fooList = new ArrayList<Zoop>(); // could come from a method
?
The list is declared as ? extends Foo
even though the runtime object's generic type is Zoop
. The compiler therefore cannot let you add anything. But you are guaranteed to be operating on Foo
objects, so you can retrieve them fine.