无法将新元素(节点)添加到ArrayList
Node 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);
}
}
最佳答案
在代码中更改此内容
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>();
}
}
关于java - 访问 ArrayList 中的引用时出现问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58546129/