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?
ArrayList<? extends A>means an ArrayList of some unknown type that extendsA.That type might not be
C, so you can’t add aCto 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 aArrayList<A>.