Saturday, May 25, 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

plot explanation - Why did Peaches&#39; mom hang on the tree? - Movies &amp; TV

In the middle of the movie Ice Age: Continental Drift Peaches' mom asked Peaches to go to sleep. Then, she hung on the tree. This parti...