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

我越是谷歌,我就越困惑。

我从CSV中引入了一个未知长度的名称列表以及其他一些细节,然后我需要将其转换为Person对象并存储在名为people的列表中,这是类Club的实例变量,其列表为成员基本上。

这是一个非常简化的版本,我需要做更复杂的事情,我需要在循环浏览文件时为每一行创建对象,然后我需要添加到列表集合中。

当我运行我的代码时,我不断收到nullPointerException错误,我很难过如何避免它。 我猜我创建新对象时我的变量p需要在每个循环上进行更改,但我认为不可能动态更改变量吗?

无法想象我每次都可以使用有效的非null引用将对象提交到集合。 非常感谢任何帮助。 我试图在下面的代码中删除所有不必要的东西。

谢谢

//class arraylist instance variable of class "Club" private ArrayList people; //class constructor for Club public Club() {List people = new ArrayList();} public void readInClubMembers() { //some variables concerning the file input String currentLine; String name; String ageGroup; while (bufferedScanner.hasNextLine()) { //some lines bringing in the scanner input from the file name = lineScanner.next(); ageGroup = "young"; Person p = new Person(); // i guess things are going wrong around here people.add(p); p.setName(name); p.setAgeGroup(ageGroup); } } 

在构造函数内部的people = …之前删除List ,否则你在构造函数中声明一个新的局部变量people遮蔽了字段 people (然后从未使用过)。 这使得class字段未初始化( 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 } }