IceCube
IceCube

Reputation: 3

Storing an ArrayList in an 2d Array Java

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!

Upvotes: 0

Views: 71

Answers (2)

Alexey Romanov
Alexey Romanov

Reputation: 170713

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 

Upvotes: 1

Bucket
Bucket

Reputation: 7521

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.

Upvotes: 0

Related Questions