【问题标题】:Adding objects to an array list - "Cannot invoke xxx.add because yyy is null" [duplicate]将对象添加到数组列表 - “无法调用 xxx.add,因为 yyy 为空”[重复]
【发布时间】:2022-01-21 03:42:08
【问题描述】:

我有一类对象:

public class SubObjects {
    
    int depth;
    
    public SubObjects(int d) {
        this.depth = d;
    }
}

然后是另一类对象:

import java.util.ArrayList;

public class Objects {
    
    private int height;
    private int width;
    ArrayList<SubObjects> liste;
    
    public Objects(int h, int w) {
        this.height = h;
        this.width = w;
    }
}

这里的想法是每个对象都应该能够保存一个高度值、一个宽度值和一个子对象列表。

例如= 2,4,[子对象1,子对象2]

以下是主要类:

import java.util.*;

public class Tryout {
    
    public static void main(String[] args) {
        SubObjects S1 = new SubObjects(7);
        SubObjects S2 = new SubObjects(9);
        
        Objects O1 = new Objects(2,4);
        O1.liste.add(S1);
        O1.liste.add(S2);
        
        System.out.println(O1);
    }
}

首先我创建了两个子对象。

然后我用整数 2 和 4 创建一个对象。

一切都误入歧途的是下一行:

O1.liste.add(S1);

给出的错误代码:

Cannot invoke "java.util.ArrayList.add(Object)" because "O1.liste" is null

现在我得到数组列表为空,当然我还没有添加任何东西,但是为什么我不能添加任何东西呢?

【问题讨论】:

  • 您只是在声明对象,而不是为其分配值。 ArrayList&lt;SubObjects&gt; liste = new ArrayList&lt;&gt;();。如果一个对象没有分配任何值,它将默认为null,而像int这样的原始变量将默认为0
  • 一定会回到那个链接,谢谢!

标签: java object arraylist null


【解决方案1】:

liste 未初始化。换句话说,它不是ArrayList - 它是null 引用。由于那里没有对象,因此您不能在其上调用任何方法。

为了解决这个问题,你可以在构造函数中初始化liste

public Objects(int h, int w) {
    this.height = h;
    this.width = w;
    this.liste = new ArrayList<>();
}

【讨论】:

    【解决方案2】:

    liste 从未初始化。如下初始化或在构造函数中初始化。

    public class Objects {
        
        private int height;
        private int width;
        ArrayList<SubObjects> liste = new ArrayList<>(); // <===add this
        
        public Objects(int h, int w) {
            this.height = h;
            this.width = w;
        }
    }
    

    【讨论】:

    • 请解释为什么他应该添加这个。
    猜你喜欢
    • 2021-03-17
    • 1970-01-01
    • 1970-01-01
    • 2012-10-30
    • 2022-01-10
    • 1970-01-01
    • 2019-03-12
    • 1970-01-01
    • 2015-12-04
    相关资源
    最近更新 更多