0

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
user2570387
  • 15
  • 1
  • 4

3 Answers3

1

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.

gaborsch
  • 15,408
  • 6
  • 37
  • 48
1

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>>();
0x6C38
  • 6,796
  • 4
  • 35
  • 47
1

I would recomend this

    ArrayList<ArrayList<Integer>> paths = new ArrayList<ArrayList<Integer>>();
        for (int i=0; i<2; ++i)
            paths.add(new ArrayList<Integer>());
pablobu
  • 1,261
  • 1
  • 12
  • 18