1

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?

0

1 Answer 1

2

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.)

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.