java 将对象添加到数组列表。尝试将对象添加到 ArrayList 时出错
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/5671610/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Add Object to array list. Get error when try add obect to ArrayList
提问by edi
Could somebody answer why there is a problem with my array list. I have a classes: List
, People
and Main
(to run everything).
有人可以回答为什么我的数组列表有问题。我有一个类:List
,People
和Main
(运行一切)。
In List
I am creating a new ArrayList
to hold objects of type People
.
在List
我创建一个 newArrayList
来保存类型的对象People
。
In Main
I am making new List object, then make new People object and then calling from List object add
method, and at this point I get a nullPointerException
exception.
在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
}
}
回答by Ben
In the constructor:
在构造函数中:
list = new ArrayList<People>();
回答by Vincent Ramdhanie
You did not instantiate the list at any time. In your constructor do this:
您没有在任何时候实例化列表。在您的构造函数中执行以下操作:
public List(){ //constructor
list = new ArrayList<People>();
}
回答by Larry Watanabe
I'm not sure if this is relevant, but it's a bad idea to name your class "List" since this will hide the List interface.
我不确定这是否相关,但将类命名为“List”是个坏主意,因为这会隐藏 List 界面。
回答by SLaks
You need to put an ArrayList
instance into your list
field.
您需要将一个ArrayList
实例放入您的list
领域。