Possible Duplicate:
Why is this strange order happens in PriorityQueue in java?
Please, see the code below:
public static void main(String[] args) {
Queue<String> q = new PriorityQueue<String>();
q.offer("car");
q.offer("airplane");
q.offer("bicycle");
Iterator<String> i = q.iterator();
while(i.hasNext())
System.out.print(i.next() + " ");
}
Can someone explain me why the output is
airplane car bicycle
instead of
airplane bicycle car
?
Since in the API it says that the elements of the priority queue are ordered according to their natural ordering.
PriorityQueue is based on a priority heap. This data structure allows to retrieve the least element very quickly though the elements are not sorted. Adding elements to PriorityQueue is faster than to TreeSet which is tree based. Since the elements are not sorted, the iterator, as API says, “does not return the elements in any particular order”.