初始化BooleanProperty的2D数组时出现NullPointerException吗?

我有一个非常简单的构造函数,其中将BooleanProperty类型的2D数组初始化为全false。但是,我在行grid[i][j].set(false)中得到了NullPointerException。我不确定为什么会这样,因为grid不为null?我想我一定不能正确使用BooleanProperty,但是我不确定为什么。

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
}
zyyzyyzhaoyiying 回答:初始化BooleanProperty的2D数组时出现NullPointerException吗?

grid不为null。它的内容是。因此,添加此行,您甚至不需要setter

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

您已经为grid对象分配了内存,但是它本身是由其他对象组成的,这些对象本身还没有分配任何东西。因此,您还必须分别为其分配内存。

,

即使您创建了BooleanProperty个引用数组,也需要初始化每个引用。试试这个:

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
}
本文链接:https://www.f2er.com/3148064.html

大家都在问