您好, 欢迎来到 !    登录 | 注册 | | 设为首页 | 收藏本站

尝试将新的Class实例添加到ArrayList时,while循环中出现NullPointerException

尝试将新的Class实例添加到ArrayList时,while循环中出现NullPointerException

删除构造函数内部的List<Person>before people = …,否则,您将在构造函数内部声明一个新的局部变量people,使该字段 成为阴影people(然后不再使用)。这使类字段未初始化(null),然后导致NPE。

相反,您想要初始化字段people

public Club() {
    // you can also use "this.people = …" to be explicit
    people = new ArrayList<>();
}

显示差异:

class Example {
    private int myNumber;

    public Example() {
        myNumber = 42; // sets the field of the class
        int myNumber = 1337; // declares a new local variable shadowing the class field
        myNumber = -13; // accesses the object in the closest scope which is the local variable
        this.myNumber = 0; // explicitly accesses the class field
    }
}
其他 2022/1/1 18:30:42 有375人围观

撰写回答


你尚未登录,登录后可以

和开发者交流问题的细节

关注并接收问题和回答的更新提醒

参与内容的编辑和改进,让解决方法与时俱进

请先登录

推荐问题


联系我
置顶