0

I'm very new to Java, and I seem to be getting some bizarre errors. I've looked everywhere for a solution, and all the solutions I've come across are identical to what I already have.

I've written a class to add a destination to an ArrayList, yet it's not working.

I'm getting this error: "Exception in thread "main" java.lang.NullPointerException"

Here's my code:

public void addDestination(String destination) {
    destinations.add(destination);
}

and the code for the data I'm trying to add to the ArrayList is this:

String temp = "test";
Agent smith = new Agent();
smith.addDestination(temp);

It quits the program in the method, and does not add the destination to the array list. Anyone got any ideas as to why? Thanks in advance.

UPDATE:
I'd initialised it to null in my default constructor, d'oh. Thanks everyone :-)

4
  • 2
    Did you initialize destinations? Commented May 6, 2013 at 17:57
  • You'll need to show more of your code. Commented May 6, 2013 at 17:58
  • Where and how have you declared the arraylist? Commented May 6, 2013 at 17:58
  • Whatever the case, your list should be initialized to new ArrayList<String>(). Commented May 6, 2013 at 18:00

3 Answers 3

3

A good practice in Java is to initialize your Collection to empty Collection instead of null in your default constructor.

Sign up to request clarification or add additional context in comments.

Comments

2

just initialize your list

List<String> destinations = new ArrayList<String>();

Comments

1

You likely did not initialize the ArrayList. The code would look something like: destinations = new ArrayList<String>();

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.