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

I then have the following ArrayLists with few elements in them

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

I created this ArrayList mix in order to contain elements of B, C or D. I then try to add an element of type C into the mix ArrayList

mix.add(anElementOfTypeC);

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 and how to resolve this? Thanks in advance.

share|improve this question
3  
From your code extract, mix is actually an ArrayList<B> here... – fge Jan 13 at 17:32
During your research - if you did some, did you came through this SO question - stackoverflow.com/questions/1910892/… ? – Rohit Jain Jan 13 at 17:36
feedback

4 Answers

You can create the array list of super class type. so you can do this.

ArrayList<A> arrayList=new ArrayList<A>();
share|improve this answer
feedback

You could just declare:

ArrayList<A> mix = new ArrayList<A>();

You can add any element of class A or any of its subclasses into such a list. It is just that when you get from that list, you will only be able to call methods available on A.

Note that A is not limited to being a "full fledged" class: it can be an abstract class or even an interface.

share|improve this answer
feedback

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

share|improve this answer
feedback

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

share|improve this answer
can't add anything is a bit too strict. We can add null, or we can add list.get(0) back to the list. I know I'm picking too much. ;) – Rohit Jain Jan 13 at 17:37
And yet you can declare Class<? extends A> c = B.class... Generics give me a real headache :/ – fge Jan 13 at 17:42
1  
@RohitJain: no, you cannot add list.get(0) back to the list – newacct Jan 13 at 20:49
feedback

Your Answer

 
or
required, but never shown
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.