Tuesday, 19 September 2017

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

casting - Why wasn&#39;t Tobey Maguire in The Amazing Spider-Man? - Movies &amp; TV

In the Spider-Man franchise, Tobey Maguire is an outstanding performer as a Spider-Man and also reprised his role in the sequels Spider-Man...