I have classes A
, B
, C
and D
where B
extends A
, C
extends A
and D
extends A
.
I have the following ArrayList
s 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?
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 .
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With