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);
                }
            }
        }
    }
2
  • 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) Commented Jul 10, 2016 at 12:52
  • Possible duplicate of What is a NullPointerException, and how do I fix it? Commented Jul 10, 2016 at 13:01

1 Answer 1

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<>();
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.