Skip to content

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.nextDouble(),;  // 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.nextDouble(),;
//      ^ BTW I think you mean `j` here.

(Combine the two steps if you like.)