将对象添加到数组列表 - "Cannot invoke xxx.add because yyy is null"
Adding objects to an array list - "Cannot invoke xxx.add because yyy is null"
我有 class 个对象:
public class SubObjects {
int depth;
public SubObjects(int d) {
this.depth = d;
}
}
然后是另一个 class 对象:
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]
以下是主要的class:
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
现在我知道数组列表是空的,当然我还没有添加任何东西,但是为什么我不能添加任何东西呢?
列表从未初始化。要么如下初始化,要么在构造函数中初始化。
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;
}
}
liste
未初始化。换句话说,它不是 ArrayList
- 它是 null
引用。由于那里没有对象,您不能对其调用任何方法。
要解决此问题,您可以在构造函数中初始化 liste
:
public Objects(int h, int w) {
this.height = h;
this.width = w;
this.liste = new ArrayList<>();
}
我有 class 个对象:
public class SubObjects {
int depth;
public SubObjects(int d) {
this.depth = d;
}
}
然后是另一个 class 对象:
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]
以下是主要的class:
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
现在我知道数组列表是空的,当然我还没有添加任何东西,但是为什么我不能添加任何东西呢?
列表从未初始化。要么如下初始化,要么在构造函数中初始化。
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;
}
}
liste
未初始化。换句话说,它不是 ArrayList
- 它是 null
引用。由于那里没有对象,您不能对其调用任何方法。
要解决此问题,您可以在构造函数中初始化 liste
:
public Objects(int h, int w) {
this.height = h;
this.width = w;
this.liste = new ArrayList<>();
}