Why does PriorityQueue.toString return the wrong element order? [duplicate]

You need to poll the items from the PriorityQueue one by one. toString doesn’t do that.

So instead of your System.out.println(queue); do this:

while(!queue.isEmpty()) {
   System.out.println(queue.poll());
}

The reason is that the PriorityQueue is never completely sorted internally, lookup how a heap works for more detail. Polling items from it fixes the heap during the calls, thus it should output the elements in sorted order.

Leave a Comment