0

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

2

3 Answers 3

3

bigList should be ArrayList<ArrayList<? extends A>> to allow this to work.

Sign up to request clarification or add additional context in comments.

Comments

0

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);

Comments

0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.