無法添加新元素(節點)到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
提交
取消