访问 ArrayList 中的引用时出现问题

无法添加新元素(节点)到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);

    }

}


人到中年有点甜
浏览 129回答 2
2回答

holdtom

在您的代码中更改此设置class Node {&nbsp; &nbsp; public int val;&nbsp; &nbsp; public String data;&nbsp; &nbsp; public ArrayList<Node> children;&nbsp; &nbsp; public Node(int val, String data) {&nbsp; &nbsp; &nbsp; &nbsp; this.val = val;&nbsp; &nbsp; &nbsp; &nbsp; this.data = data;&nbsp; &nbsp; &nbsp; &nbsp; this.children = new ArrayList<Node>();&nbsp; &nbsp; }}

catspeake

在 Node 构造函数中,您正在创建 Children 的新本地属性如果您在构造函数中进行以下更改,它将正常工作 this.children = new ArrayList();
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Java