有人可以回答为什么我的数组列表有问题吗?我有一个类:List
、People
和 Main
(运行所有内容)。
在List
中,我正在创建一个新的ArrayList
来保存People
类型的对象。
在Main
中,我正在创建新的List对象,然后创建新的People对象,然后从List对象调用add
方法,此时我得到一个 nullPointerException
异常。
public class Main {
public static void main(String[] args) {
List l = new List(); // making new List object
People p = new People(); // making new People object
l.addPeople(p); // calling from List object "addPeople" method and
}
// parsing People object "p"
}
import java.util.ArrayList;
public class List {
public List(){ //constructor
}
ArrayList<People>list; // new ArrayList to hold objects of type "People"
public void addPeople(People people){
list.add(people); // I get error here
}
}
public class People {
public People(){ // constructor
}
}
最佳答案
在构造函数中:
list = new ArrayList<People>();
关于java - 将对象添加到数组列表。尝试将对象添加到 ArrayList 时出现错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5671610/