亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

訪問 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 關注
  • 187 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號