簡體   English   中英

添加新節點的 LinkedList 數組

[英]Array of LinkedList adding new nodes

我通過以下方式創建了一個數組(使用此方法的第二個答案):

public static LinkedList<Connection>[] map;
...  // later ....
map = (LinkedList<Connection>[]) new LinkedList[count];

當我運行我的程序時,我在這個for循環內的行中得到一個 NullPointerException:

for (int j = 0; j < numOfConnections; j++) {
    map[i].add(new Connection(find(s.next()), s.nextDouble(), s.next()));  // NPE!
}

有人可以告訴我為什么拋出這個異常嗎?

創建數組時,您的map充滿了null 您需要自己初始化每個成員。

// Initialize.
for (int j = 0; j < numOfConnections; j++) {
//                  ^ I assume this means 'count' here.
    map[j] = new LinkedList<Connection>();
}

// Fill
for (int j = 0; j < numOfConnections; j++) {
    map[j].add(new Connection(find(s.next()), s.nextDouble(), s.next()));
//      ^ BTW I think you mean `j` here.
}

(如果你喜歡,可以結合這兩個步驟。)

我通過以下方式創建了一個數組(使用此方法的第二個答案):

public static LinkedList<Connection>[] map;
...  // later ....
map = (LinkedList<Connection>[]) new LinkedList[count];

當我運行程序時,我在此for循環內的行上收到NullPointerException:

for (int j = 0; j < numOfConnections; j++) {
    map[i].add(new Connection(find(s.next()), s.nextDouble(), s.next()));  // NPE!
}

有人可以告訴我為什么拋出此異常嗎?

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM