NullPointerException in while loop when trying to add new Class instances to ArrayList

折月煮酒 提交于 2019-12-02 13:17:19

Remove the List<Person> before people = … inside the constructor, otherwise you are declaring a new local variable people inside the constructor shadowing the field people (which is then never used). This leaves the class field uninitialized (null) and then causes the NPE.

What you want instead is initializing the field people:

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

To show the difference:

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
    }
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!