将对象添加到数组列表.尝试将obect添加到ArrayList时获取错误

edi*_*edi 2 java arraylist

有人可以回答为什么我的数组列表有问题.我有一个类:List,PeopleMain(用来运行所有程序).

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
    }
}
Run Code Online (Sandbox Code Playgroud)

Ben*_*Ben 6

在构造函数中:

list = new ArrayList<People>();
Run Code Online (Sandbox Code Playgroud)