0

I tried to create two dimensional ArrayList i get NullPointerException in 7 line

ArrayList<Integer>[] g = new ArrayList[500];
    for(int i = 1;i < HEIGHT - 1; i++){
        for(int j = 1;j < WIDTH - 1; j++){
            if(MAP[i][j] == 0){
                int cur = i * HEIGHT + j;
                if(MAP[i+1][j] == 0){
                    g[cur].add(cur + HEIGHT);
                }
                if(MAP[i-1][j] == 0){
                    g[cur].add(cur - HEIGHT);
                }
                if(MAP[i][j+1] == 0){
                    g[cur].add(cur + 1);
                }
                if(MAP[i][j-1] == 0){
                    g[cur].add(cur - 1);
                }
            }
        }
    }
Medet
  • 63
  • 1
  • 10
  • 2
    That's an empty array with 500 null pointers that could point to array lists, but you need to assign arraylists to each of the 500 first (in a for-loop, presumably) – Erwin Bolwidt Jul 10 '16 at 12:52
  • Possible duplicate of [What is a NullPointerException, and how do I fix it?](http://stackoverflow.com/questions/218384/what-is-a-nullpointerexception-and-how-do-i-fix-it) – ΦXocę 웃 Пepeúpa ツ Jul 10 '16 at 13:01

1 Answers1

2

If you use your debugger, you should be able to see that this doesn't create an ArrayList only an array of references to them which are all null

What you intended was

List<Integer>[] g = new ArrayList[500];
for (int i = 0; i < g.length; i++)
    g[i] = new ArrayList<>();
Peter Lawrey
  • 525,659
  • 79
  • 751
  • 1,130