From Java documentation:
The remove() and poll() methods remove and return the head of the queue.
The element() and peek() methods return, but do not remove, the head of the queue.
From the second point it says method peek()
returns head element of queue then how come its not returning head element of queue in the following program?
public class PQ {
public static void main(String[] args) {
PriorityQueue<String> pq = new PriorityQueue<String>();
pq.add("carrot");
pq.add("apple");
pq.add("banana");
System.out.println(pq.poll() + ":" + pq.peek()); // prints apple and banana rather than apple and apple
}
}
Once the first element(carrot) is removed, apple becomes the head of queue(according to FIFO in queue) so peek()method should return apple right?
Example2:
public class PQ {
public static void main(String[] args) {
PriorityQueue<String> pq = new PriorityQueue<String>();
pq.add("carrot");
pq.add("apple");
pq.add("banana");
System.out.println(pq); // prints [apple, carrot, banana] -> it should be [apple, banana, carrot] right? if it is following natural sorting order
}
}
Because you are polling first
System.out.println(pq.poll() + ":" + pq.peek());
As it is a priority queue elements are stored as
carrot -> banana -> apple
When you poll()
you get apple
and is removed from queue. After which head of queue is banana
which is exactly what you get when you peek()
.
please look at the example 2 in updated question. Sorting is strange
It's just what you don't expect. You can see the documentation
The Iterator provided in method iterator() is not guaranteed to traverse the elements of the priority queue in any particular order. If you need ordered traversal, consider using Arrays.sort(pq.toArray()).
You will understand this better if you read priority heap data structure which java priority queue use. You should use poll(), peek()
methods to get ordered data.