import java.util.*;
class Priority{
public static void main(String args[]){
PriorityQueue queue=new PriorityQueue();
queue.add(\"Amit\
PriorityQueue
doesn't store the elements in sorted order, but it allows you to get the elements from it in sorted order. It just makes sure that the the element at the head is the least element as per the ordering used for it.
So, if you store multiple numbers - 2, 1, 4, 3, 6, 8
, it will make sure that 1
is the next element you remove. Then when you remove 1
, it moves 2
to head. It doesn't bother about the ordering of rest of the elements.
This question is answered in the Javadoc:
The Iterator provided in method iterator() is not guaranteed to traverse the elements of the priority queue in any particular order.
To traverse the PQ in sorted order you have to use the remove()
method.
Most of the time a priority queue is implemented using a heap datastructure. A heap is a tree which guarantees that
if A is parent of B , then A < B
It doesnt guarantee any other ordering. It is sufficient to provide the minimum element in constant time, to add an element in log time and to remove the key in log time.
It just happen that the iterator itr
traverses the heap using a pre-order transversal.
Traverse(node)
visit(node)
Traverse(node.left())
Traverse(node.right())
Which explains your result.
note: In java <
is provided by implementing Comparable<T>