0

How can I store an ArrayList in a two dimensional array?

I've tried it like this, but it won't work:

ArrayList<Integer> arrList = new ArrayList<Integer>();
ArrayList<Integer>[][] arr = new ArrayList<Integer>[9][9];

but it won't even let me declare the ArrayList-Array.

Is there a way to store a list in a 2d array?

Thanks in advance!

5
  • Im a bit confused, do you want a 2d primitive array or a 2d arraylist, or an arraylist of primitive arrays? Commented Jun 1, 2018 at 18:49
  • I want an 2d array, in which i can store an arraylist. E.g. array[0][0]=arrayList1, array[0][1]=arrayList2 etc. Do you understand what I mean? Commented Jun 1, 2018 at 18:52
  • Try to use ArrayList<ArrayList<Integer>> a = new ArrayList<ArrayList<Integer>>(); Commented Jun 1, 2018 at 18:52
  • 1
    primitive arrays can only store primitives Commented Jun 1, 2018 at 18:53
  • ok thank you, I'll try something else Commented Jun 1, 2018 at 18:56

2 Answers 2

1

You can't create arrays of generic types in Java. But this compiles:

ArrayList<Integer> arrList = new ArrayList<Integer>();
ArrayList<Integer>[][] arr = (ArrayList<Integer>[][]) new ArrayList[9][9];
arr[0][0] = arrList;

Why can't you create these arrays? According to the Generics FAQ, because of this problem:

Pair<Integer,Integer>[] intPairArr = new Pair<Integer,Integer>[10]; // illegal 
Object[] objArr = intPairArr;  
objArr[0] = new Pair<String,String>("",""); // should fail, but would succeed 
Sign up to request clarification or add additional context in comments.

1 Comment

This helps! Thank you!
0

Assuming you want an ArrayList inside an ArrayList inside yet another ArrayList, you can simply specify that in your type declaration:

ArrayList<ArrayList<ArrayList<Integer>>> foo = new ArrayList<ArrayList<ArrayList<Integer>>>();

Entries can be accessed via:

Integer myInt = foo.get(1).get(2).get(3);

Just be wary of boundaries - if you try to access an out of bounds index you'll see Exceptions thrown.

1 Comment

thank you for your answer, but I don't want to store my ArrayList in another ArrayList. I'd like to know if it's possible to store a list in a 2d array, so that I alltogether get somthing 3d, if you know what i mean

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.