【问题标题】:NullPointerException error when trying to add to ArrayList [duplicate]尝试添加到 ArrayList 时出现 NullPointerException 错误 [重复]
【发布时间】: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? 的重复问题,因为尽管我们无法重现此问题,但解决方案仍然与重复问题相同:确保在使用@ 之前正确初始化loggedInList 987654334@。这可以在声明级别 private ArrayList&lt;Member&gt; loggedInList = new ArrayList&lt;&gt;(); 完成,这将确保始终初始化此列表,除非不同位置的 OP 将其显式设置为 null。

标签: java arraylist bluej


【解决方案1】:

我相信你没有使用正确的构造函数。您的代码中可能有一个默认的无参数构造函数。

无论如何,你都应该按照下面的代码来做。

   Website website = new Website ("someString value");
website.memberLogin (objectCreatedMember);

【讨论】:

猜你喜欢
  • 2022-01-19
  • 2014-04-02
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-04-16
  • 2015-04-09
  • 2018-08-12
  • 2023-03-22
相关资源
最近更新 更多