将对象添加到数组列表。尝试将对象添加到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
    }
}
    
已邀请:
在构造函数中:
list = new ArrayList<People>();
    
您没有在任何时候实例化该列表。在您的构造函数中执行以下操作:
   public List(){           //constructor
          list = new ArrayList<People>();
   }
    
我不确定这是否相关,但是将您的类命名为“ List \”不是一个好主意,因为这会隐藏List接口。     
您需要在
list
字段中放入
ArrayList
实例。     

要回复问题请先登录注册