【发布时间】:2018-05-25 09:44:18
【问题描述】:
在登录到网站类时,尝试将对象成员添加到 ArrayList loggedInList。
public class Website
{
// The name of the website.
private String name;
// The number of hits on the website.
public int hits;
// The amount of money taken at the checkout.
private double salesTotal;
//
private ArrayList<Member> loggedInList;
是我的网站类的代码。
public Website(String newName)
{
// Intialises the name of the website.
name = newName;
// Intialises the number of hits on the site.
hits = 0;
// Intialises the amount of money taken at the checkout.
salesTotal = 0;
//
loggedInList = new ArrayList<Member>();
}
是网站类的构造函数。
public void memberLogin(Member member)
{
member.setLoginStatus(true);
member.setWebsite(this);
System.out.println(name + " welcomes member " + member.getMembershipNumber() + "," + " you are now logged in.");
member.setWebsite(this);
hits +=1;
loggedInList.add(member);
}
是应该将当前成员添加到 ArrayList 中的方法。
我得到的错误是一个 NullPointerException 就行了:
loggedInList.add(member);
我真的不知道为什么。
【问题讨论】:
-
使用前先构建列表
-
^ 看起来他们正在从粘贴的代码中这样做......
-
你班上还有什么地方用
loggedInList做事?也许您在施工后的某个时间将其设置为null?您发布的代码应该可以工作。你能edit你的问题提供minimal reproducible example吗?也许你没有调用你认为的代码...... -
伙计们,将
null添加到ArrayList是完全有效的,所以无论如何不可能。loggedInList必须为空。 -
我决定将此问题投票为What is a NullPointerException, and how do I fix it? 的重复问题,因为尽管我们无法重现此问题,但解决方案仍然与重复问题相同:确保在使用@ 之前正确初始化
loggedInList987654334@。这可以在声明级别private ArrayList<Member> loggedInList = new ArrayList<>();完成,这将确保始终初始化此列表,除非不同位置的 OP 将其显式设置为 null。