Medet
Medet

Reputation: 73

NullPointer in Arraylist java

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

Upvotes: 0

Views: 62

Answers (1)

Peter Lawrey
Peter Lawrey

Reputation: 533492

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

Upvotes: 2

Related Questions