Strange nullpointer exception error when i use a L

2019-09-06 04:06发布

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条回答
Explosion°爆炸
2楼-- · 2019-09-06 04:54

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.

查看更多
登录 后发表回答