简体   繁体   中英

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 (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. 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 (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?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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