Add Object to array list. Get error when try add obect to ArrayList
Could somebody answer why there is a problem with my array list. I have a classes: List
, People
and Main
(to run everything).
In List
I am creating a new ArrayList
to hold objects of type 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.
public class Main {
public static void main(String[] args) {
List l = new List(); // making new List object
People p = new People(); // making new People objec开发者_如何转开发t
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
}
}
In the constructor:
list = new ArrayList<People>();
You did not instantiate the list at any time. In your constructor do this:
public List(){ //constructor
list = new ArrayList<People>();
}
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.
You need to put an ArrayList
instance into your list
field.
精彩评论