【发布时间】:2023-03-05 20:43:02
【问题描述】:
有人可以回答为什么我的数组列表有问题吗?我有一个课程: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
}
}
【问题讨论】:
-
谢谢大家,我以为是构造函数有问题,只是不明白在哪里。现在它可以工作了,再次感谢大家。