简体   繁体   English

添加新节点的 LinkedList 数组

[英]Array of LinkedList adding new nodes

I've created an array (using the second answer from this method ) by:我通过以下方式创建了一个数组(使用此方法的第二个答案):

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

And when I run my program, I get a NullPointerException at the line inside this for loop:当我运行我的程序时,我在这个for循环内的行中得到一个 NullPointerException:

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

Can someone please tell me why this exception is thrown?有人可以告诉我为什么抛出这个异常吗?

Your map is full of null when an array is created.创建数组时,您的map充满了null You need to initialize each member yourself.您需要自己初始化每个成员。

// 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.
}

(Combine the two steps if you like.) (如果你喜欢,可以结合这两个步骤。)

I've created an array (using the second answer from this method ) by:我通过以下方式创建了一个数组(使用此方法的第二个答案):

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

And when I run my program, I get a NullPointerException at the line inside this for loop:当我运行程序时,我在此for循环内的行上收到NullPointerException:

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

Can someone please tell me why this exception is thrown?有人可以告诉我为什么抛出此异常吗?

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM