简体   繁体   中英

How to create a 2D ArrayList?

I'm trying to use Java to create a 2-dimensional array. The size of rows is known, while the size of columns is unknown. Here is my code and it doesn't work. Could anyone give me some idea?

ArrayList<Integer> paths[];
paths = new ArrayList[2];// 2 paths
for (int i=0; i<2; ++i)
    paths[i].add(1); // add an element to each path

Initialize the array element before adding to it. Put the initialization into the for loop:

@SuppressWarnings("unchecked")
ArrayList<Integer>[] paths = new ArrayList[2];

for (int i=0; i<2; ++i) {
    paths[i] = new ArrayList<Integer>();
    paths[i].add(1);
}

This way you can avoid the NullPointerException .

This is a "2d" ArrayList :

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

And here is the non-diamond operator version for Java < 1.7:

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

I would recomend this

    ArrayList<ArrayList<Integer>> paths = new ArrayList<ArrayList<Integer>>();
        for (int i=0; i<2; ++i)
            paths.add(new ArrayList<Integer>());

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