ArrayList error, Exception in thread & ldquo; hand & rdquo; java.lang.NullPointerException

advertisements

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


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