简体   繁体   中英

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!

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 

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM