将对象添加到数组列表。尝试将对象添加到ArrayList时出错
|
有人可以回答为什么我的数组列表有问题。我有一个类:
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
}
}
没有找到相关结果
已邀请:
4 个回复
布埃郝卞簿
可扇胆
漂汀拦
纤洞需匪
字段中放入
实例。