无法添加新元素(节点)到ArrayListNode N = new Node(5,"Sandeep");Node N1 = new Node(5,"qwert");在下面的行中我收到空指针异常N.children.add(N1)代码:class Node { public int val; public String data; public ArrayList<Node> children; public Node(int val, String data) { this.val = val; this.data = data; ArrayList<Node> children = new ArrayList<Node>(); }}public class Nary { public static void main(String[] args) { // ArrayList<Node> children = new ArrayList<Node>(); Node N = new Node(5,"Sandeep"); Node N1 = new Node(5,"qwert"); N.children.add(N1); }}
2 回答
holdtom
TA贡献1805条经验 获得超10个赞
在您的代码中更改此设置
class Node {
public int val;
public String data;
public ArrayList<Node> children;
public Node(int val, String data) {
this.val = val;
this.data = data;
this.children = new ArrayList<Node>();
}
}
catspeake
TA贡献1111条经验 获得超0个赞
在 Node 构造函数中,您正在创建 Children 的新本地属性如果您在构造函数中进行以下更改,它将正常工作 this.children = new ArrayList();
添加回答
举报
0/150
提交
取消