NullPointerException when trying to add an object to PriorityQueue

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

i initialize the queue:

private PriorityQueue<NodeObject> nodes;

and here I am trying to add to it:

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

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

+3
source share
3 answers

You did not initialize the queue.

nodes = new SomePriorityQueue();
+6
source

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

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

nodes ( nodes = new PriorityQueue<NodeObject>();) . , Java , , , , nodes null, , -.

+3

; nodes == null. NullPointerException nodes.add.

- PriorityQueue<NodeObject> nodes. :

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

JLS 4.12.5

  • , :
    • null.
+1
source

Source: https://habr.com/ru/post/1742923/


All Articles