简体   繁体   中英

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

Java的一个好习惯是将您的Collection初始化为空Collection,而不是默认构造函数中的null。

只需初始化您的列表

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM