views:

98

answers:

3

i keep getting a null pointer exception when trying to add an object to a priority queue

i initialize the queue:

private PriorityQueue<NodeObject> nodes;

and here i try to add to it:

NodeObject childNode = new NodeObject(child, 1);
nodes.add(childNode);

why doesn't this work? i know my NodeObject is not null because i create it right before i add it.

+4  A: 

You haven't initialized the queue.

nodes = new SomePriorityQueue();
mkorpela
+3  A: 

The problem is that you forgot to initialize your priority queue nodes. Change it to:

private PriorityQueue<NodeObject> nodes = new PriorityQueue<NodeObject>();

Or explicitly allocate nodes (as in nodes = new PriorityQueue<NodeObject>();) in each of your constructors. Keep in mind that in Java, any type that isn't a primitive is actually an implicit pointer, so while the pointer nodes has been initialized to null, it has not been initialized to point to something.

Michael Aaron Safyan
+1  A: 

You didn't actually create a priority queue; nodes == null. This causes NullPointerException to be thrown when you try to invoke nodes.add.

The way to fix this is by actually constructing a PriorityQueue<NodeObject>, and assigning the reference to it to nodes. You can do this in the declaration as follows:

private PriorityQueue<NodeObject> nodes = new PriorityQueue<NodeObject>();
                                        ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^

JLS 4.12.5 Initial Values of Variables

  • Each class variable, instance variable, or array component is initialized with a default value when it is created:
    • For all reference types, the default value is null.
polygenelubricants
but when i initialize it i get a stack overflow error
meagan
That's another problem entirely. Where do you get the error? What line? Give us the full exception message, and the line in the code where the message says the error comes from (and a few lines surrounding it for context). Simply instantiating a `java.util.PriorityQueue<E>` should not throw a `StackOverflowError`. Are you doing any sort of recursion too by any chance?
polygenelubricants