人到中年有點(diǎn)甜
2023-12-13 14:34:47
無(wú)法添加新元素(節(jié)點(diǎn))到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貢獻(xiàn)1805條經(jīng)驗(yàn) 獲得超10個(gè)贊
在您的代碼中更改此設(shè)置
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貢獻(xiàn)1111條經(jīng)驗(yàn) 獲得超0個(gè)贊
在 Node 構(gòu)造函數(shù)中,您正在創(chuàng)建 Children 的新本地屬性如果您在構(gòu)造函數(shù)中進(jìn)行以下更改,它將正常工作 this.children = new ArrayList();
添加回答
舉報(bào)
0/150
提交
取消