Saturday 25 May 2019

java - NullPointerException when initialising a 2D array of BooleanProperty?




I have a very simple constructor where I initialise a 2D array of type BooleanProperty to all false. However, I am getting a NullPointerException at the line grid[i][j].set(false). I am not sure why this is the case, as grid is not null? I think I must be using BooleanProperty incorrectly, but I'm not sure why.



public class Game {
private BooleanProperty[][] grid;

public Game() {
grid = new BooleanProperty[10][10];
for (int i = 0; i < 10; i++) {
for (int j = 0; j < 10; j++) {
grid[i][j].set(false);
}
}
}

// other methods
}

Answer



Even though you have created the array of BooleanProperty references, you need to initialize each one. Try this:



public class Game {
private BooleanProperty[][] grid;

public Game() {
grid = new BooleanProperty[10][10];
for (int i = 0; i < 10; i++) {
for (int j = 0; j < 10; j++) {
BooleanProperty p = new SimpleBooleanProperty();
p.set(false);
grid[i][j] = p;
}
}
}

// other methods
}

No comments:

Post a Comment

php - file_get_contents shows unexpected output while reading a file

I want to output an inline jpg image as a base64 encoded string, however when I do this : $contents = file_get_contents($filename); print &q...