Strange nullpointer exception error when i use a List

杀马特。学长 韩版系。学妹 提交于 2019-12-25 03:13:23

问题


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.



来源:https://stackoverflow.com/questions/4208744/strange-nullpointer-exception-error-when-i-use-a-list

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!