问题
This is the code and the output is below it why do the value "5" and "6" i mean how are the new priorities set after poll method in a PriorityQueue (similarly the other elements in the queue) . I am preparing for java certification exam and i always tend to choose the wrong answer due to this concept, any help is welcomed.
import java.util.*;
public class PriorityQueueDemo {
public static void main(String args[]) {
// create priority queue
PriorityQueue < Integer > prq = new PriorityQueue < Integer > ();
// insert values in the queue
for ( int i = 3; i < 10; i++ ){
prq.add (new Integer (i)) ;
}
System.out.println ( "Initial priority queue values are: "+ prq);
// get the head from the queue
Integer head = prq.poll();
System.out.println ( "Head of the queue is: "+ head);
System.out.println ( "Priority queue values after poll: "+ prq);
}
}
Output :
Initial priority queue values are: [3, 4, 5, 6, 7, 8, 9]
Head of the queue is: 3
Priority queue values after poll: [4, 6, 5, 9, 7, 8]
回答1:
The values haven't changed, they are just printed in a different order.
The toString() for PriorityQueue
returns the elements in the order they are returned by its Iterator
. If you read the Javadoc for PriorityQueue#iterator() you see the following:
Returns an iterator over the elements in this queue. The iterator does not return the elements in any particular order.
So, you can't draw any conclusions from your printouts, since no effort is being made by the PriorityQueue
to print them in any particular order, by priority or otherwise.
回答2:
Per the docs, poll()
Retrieves and removes the head of this queue, or returns null if this queue is empty.
If you want to peek at the head without removing it, call peek()
Retrieves, but does not remove, the head of this queue, or returns null if this queue is empty.
Order: A priority queue achieves high performance [O(log(n)) time for the enqueing and dequeing, constant time for the retrieval] by not sorting all of its elements. It only does a partial sort to get the least element to the head position. So when the inherited AbstractCollection#toString()
method iterates through the elements, only the first one is in sorted order. When you remove the head element, some more sorting happens and the other elements change relative positions.
See Wikipedia for how priority queues work.
回答3:
For exam remember that PriorityQueue always make the first entry in correct order and rest of the entries can be in any order because
The Iterator provided in method iterator() is not guaranteed to traverse the elements of the priority queue in any particular order.
This trick saved my time to answer some trick question on exam
来源:https://stackoverflow.com/questions/25927009/why-do-the-values-inside-the-priorityqueue-change-after-the-poll-method-in-java