我使用列表时出现奇怪的nullpointer异常错误 [英] Strange nullpointer exception error when i use a List

查看:73
本文介绍了我使用列表时出现奇怪的nullpointer异常错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用的是<Friend>列表,朋友"是我所拥有的类,其中包含有关人,姓名,描述等的信息...

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

好吧,我在friends.add(a);

有人可以解释为什么吗?

can someone explain why?

谢谢

推荐答案

因为您尚未初始化friends.仍然是null.

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.

这篇关于我使用列表时出现奇怪的nullpointer异常错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆