Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java Generic with ArrayList <? extends A> add element

I have classes A, B, C and D where B extends A, C extends A and D extends A.

I have the following ArrayLists each with a few elements in them:

ArrayList<B> b; ArrayList<? extends A> mix = b; 

I intended for the variable mix to contain elements of type B, C or D. I tried to add an element of type C into mix like this:

mix.add(anElementOfTypeC); 

But the IDE doesn't allow me to do so and it says:

anElementOfTypeC cannot be converted to CAP#1 by method of invocation conversion where CAP#1 is a fresh type-variable: CAP#1 extends A from capture of ? extends A

Did I use the <? extends A> correctly? How can I resolve this?

like image 664
vda8888 Avatar asked Jan 13 '13 17:01

vda8888


People also ask

What does <? Super t mean in Java?

super T denotes an unknown type that is a supertype of T (or T itself; remember that the supertype relation is reflexive). It is the dual of the bounded wildcards we've been using, where we use ? extends T to denote an unknown type that is a subtype of T .

How do you add an element to a generic list in Java?

Accessing a Generic List. You can get and insert the elements of a generic List like this: List<String> list = new ArrayList<String>; String string1 = "a string"; list. add(string1); String string2 = list.


2 Answers

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>.

like image 169
SLaks Avatar answered Oct 11 '22 13:10

SLaks


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.

like image 26
Dmitry Zaytsev Avatar answered Oct 11 '22 13:10

Dmitry Zaytsev