0

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
}
scott
  • 25
  • 4

2 Answers2

3

grid isn't null. Its contents are. So add this line and you won't even need the setter:

grid[i][j] = new SimpleBooleanProperty(false); // Or whatever constructor or builder or factory method you want to use  

You have allocated memory for the grid object but it itself is made up of other objects, which themselves, haven't been allocated anything. So you have to allocate memory to them individually as well.

Shankha057
  • 1,194
  • 18
  • 33
3

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
}
Nick Clark
  • 1,264
  • 1
  • 15
  • 22
  • 1
    To follow up, BooleanProperty is an abstract class. The bare bones implementation class is SimpleBooleanProperty. For most cases, this does the trick. – Nick Clark Nov 07 '19 at 01:40