user2570387
user2570387

Reputation: 15

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

Upvotes: 0

Views: 4843

Answers (3)

0x6C38
0x6C38

Reputation: 7076

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>>();

Upvotes: 1

pablobu
pablobu

Reputation: 1301

I would recomend this

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

Upvotes: 1

gaborsch
gaborsch

Reputation: 15758

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.

Upvotes: 1

Related Questions