Tom Sheedy
Tom Sheedy

Reputation: 1

ArrayList error, Exception in thread "main" java.lang.NullPointerException

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 :-)

Upvotes: 0

Views: 5417

Answers (3)

Max Vasileuski
Max Vasileuski

Reputation: 2651

just initialize your list

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

Upvotes: 2

James T
James T

Reputation: 627

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

Upvotes: 1

Arnaud Denoyelle
Arnaud Denoyelle

Reputation: 31225

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

Upvotes: 3

Related Questions