yoseph1998
yoseph1998

Reputation: 355

Adding an arrayList of random type to an arrayList

So I have looked a lot online on how to do this and what I get is this

ArrayList<ArrayList<Type>> arrayLists = new ArrayList<ArrayList<Type>>();
ArrayList<TypeA> typeA = new ArrayList<TypeA>();
ArrayList<TypeB> typeB = new ArrayList<TypeB>();
...

Assuming that I have a class called TypeA, and a class called TypeB, and the array list typeA would contain multiple objects of the class TypeA. The same goes for typeB

Now my question what do I put where Type is for the arrayList, and how do I add an arrayList to arrayLists? If I did this I would get an error:

arrayLists.add(typeA);

I am trying to make a list that contains arrayLists, if my approach is wrong please tell me.

Upvotes: 1

Views: 59

Answers (1)

If you want an ArrayList which contains ArrayLists with unknown contents, use the type ArrayList<ArrayList<?>> for the outer list.

This code should compile with no problems:

ArrayList<ArrayList<?>> arrayLists = new ArrayList<ArrayList<?>>();
ArrayList<TypeA> typeA = new ArrayList<TypeA>();
ArrayList<TypeB> typeB = new ArrayList<TypeB>();

arrayLists.add(typeA);
arrayLists.add(typeB);

Upvotes: 4

Related Questions