As per the definition of PriorityQueue, it says :
The elements of the priority queue are ordered according to their natural ordering, or by a Comparator provided at queue construction time, depending on which constructor is used.
But when I am trying with 3 elements in the Queue, the elements does not appear to be sorted properly.
Queue<Integer> q2 = new PriorityQueue<Integer>();
q2.add(9);
q2.add(7);
q2.add(8);
Iterator<Integer> i = q2.iterator();
while(i.hasNext()){
Integer e = i.next();
System.out.println(e);
}
Output :
7
9
8
[edit] If the number of elements is 4, the sorting appears to be correct
q2.add(9);
q2.add(7);
q2.add(8);
q2.add(5);
Iterator<Integer> i = q2.iterator();
while(i.hasNext()){
Integer e = i.next();
System.out.println(e);
}
Outputs:
5
7
8
9