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?