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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-30 12:12:39  来源:igfitidea点击:

Add Object to array list. Get error when try add obect to ArrayList

javaarraylist

提问by edi

Could somebody answer why there is a problem with my array list. I have a classes: List, Peopleand Main(to run everything).

有人可以回答为什么我的数组列表有问题。我有一个类:ListPeopleMain(运行一切)。

In ListI am creating a new ArrayListto hold objects of type People.

List我创建一个 newArrayList来保存类型的对象People

In MainI am making new List object, then make new People object and then calling from List object addmethod, and at this point I get a nullPointerExceptionexception.

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 ArrayListinstance into your listfield.

您需要将一个ArrayList实例放入您的list领域。