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?
Advertisement
Answer
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.)