Strange nullpointer exception error when i use a L

2019-09-06 04:13发布

问题:

i am using a List of <Friend>, Friend is a class that i have with some info about a person, name, desc, etc...

ok, this is the code on the start of the class:

private List<Friend> friends;

and later... in a method of the class:

Friend a = new Friend("Pablo SáeZ", "Total", "39.68333", "-0.32667", new Date());
friends.add(a);

ok, i have the nullpointerexception on the line friends.add(a);

can someone explain why?

thanks

回答1:

Because you haven't initialized friends yet. It's still null.

You need to initialize it before using.

friends = new ArrayList<Friend>();

A common place to do this job is the class' constructor.