2

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 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
    }
}
1
  • Thanks everyone, I thought that there is problem in constructor just could not understand where. Now it works, thank a lot to all once more time. Commented Apr 15, 2011 at 2:04

4 Answers 4

6

In the constructor:

list = new ArrayList<People>();
Sign up to request clarification or add additional context in comments.

Comments

2

You did not instantiate the list at any time. In your constructor do this:

   public List(){           //constructor
          list = new ArrayList<People>();
   }

Comments

2

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.

2 Comments

That's just for testing, in big program I wouldn't.
@Edgar You'd better never do that. The only things you can "gain" is to confuse yourself (and the people you show it to) and to have to rewrite it for use in a "big program".
1

You need to put an ArrayList instance into your list field.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.