Java Generic with ArrayList <? extends A> add element
ArrayList<? extends A>
means an ArrayList of some unknown type that extends A
.
That type might not be C
, so you can't add a C
to the ArrayList.
In fact, since you don't know what the ArrayList is supposed to contain, you can't add anything to the ArrayList.
If you want an ArrayList that can hold any class that inherits A
, use a ArrayList<A>
.
It is not possible to add elements in collection that uses ? extends
.
ArrayList<? extends A>
means that this is an ArrayList
of type (exactly one type) that extends A
. So you can be sure, that when you call get
method, you'll get something that is A. But you can't add something because you don't know what exactly the ArrayList
contains.
Did I use the
<? extends A>
correctly?
List<? extends A> list;
means that the 'list' refers to an object implemented interface List, and the list can hold elements inherited from class A (including A). In other words the following statements are correct:
List<? extends A> listA1 = new ArrayList<A>();
List<? extends A> listB1 = new ArrayList<B>();
List<? extends A> listC1 = new ArrayList<C>();
List<? extends A> listD1 = new ArrayList<D>();
Java generics are a compile-time strong type checking. The compiler uses generics to make sure that your code doesn't add the wrong objects into a collection.
You tried to add C
in ArrayList<B>
listB1.add(new C());
If it were allowed the object ArrayList<B>
would contain different object types (B,C).
That is why the reference listB1 works in 'read-only' mode. Additionally you could take a look at this answer.
how to resolve this?
List<A> list = new ArrayList<A>();