为了账号安全,请及时绑定邮箱和手机立即绑定

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

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

人到中年有点甜 2023-12-13 14:34:47
无法添加新元素(节点)到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>();

    }


}


查看完整回答
反对 回复 2023-12-13
?
catspeake

TA贡献1111条经验 获得超0个赞

在 Node 构造函数中,您正在创建 Children 的新本地属性如果您在构造函数中进行以下更改,它将正常工作 this.children = new ArrayList();



查看完整回答
反对 回复 2023-12-13
  • 2 回答
  • 0 关注
  • 63 浏览

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信