Reputation: 936
assume I have Class A as the parent of Class B and Class C
I initialized two ArrayList<B>
bList and ArrayList<C>
cList.
Then I have another ArrayList<ArrayList<A>>
bigList.
I want to store bList and cList into that bigList by bigList.add(bList) and bigList.add(cList), and this gives me an error. Anyone have suggestion of how I should fix this or another way of doing it?
Thank you
Upvotes: 0
Views: 539
Reputation: 42597
To create a list of lists in this situation, you need to use <? extends A>
to allow subclasses of A, not just A itself.
List<B> blist = new ArrayList<B>();
List<C> clist = new ArrayList<C>();
List<List<? extends A>> listofalist = new ArrayList<List<? extends A>>();
listofalist.add(blist);
listofalist.add(clist);
If instead you want to copy the contents of the B and C lists into the A list, then you need to use ArrayList.addAll()
, not add()
.
add(Object o)
is for adding individual objects to a list.
addAll(Collection c)
is for adding all the contents of one list into another list (or other Collection).
See the javadoc for ArrayList.
Upvotes: 0
Reputation: 198033
bigList
should be ArrayList<ArrayList<? extends A>>
to allow this to work.
Upvotes: 3
Reputation: 3034
Simply based on what you just wrote, your problem could be that you're trying to this:
bigList.add(aList);
When you mean to do this:
bigList.add(bList);
Upvotes: 0