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.
However, in the following example, when I print the whole queue at once, the queue's elements are printed in random order. On the other hand, if I poll the elements one by one they are printed in natural order.
Could someone explain me this ambiguious behavior? Or Am I missing something?
public class QueueExample {
public static class Employee implements Comparable<Employee>{
private int id;
private String name;
public Employee(int id, String name){
this.id=id;
this.name=name;
}
public String toString(){
return "id:"+id+" name:"+name;
}
public int compareTo(Employee emp){
return name.compareTo(emp.name);
}
}
public static void main(String[] args) {
Queue<Employee> priority=new PriorityQueue<Employee>();
priority.add(new Employee(101, "Atlas"));
priority.add(new Employee(102, "Ztlas"));
priority.add(new Employee(101, "Ftlas"));
priority.add(new Employee(101, "Ptlas"));
System.out.println(priority);
System.out.println(priority.poll());
System.out.println(priority.poll());
System.out.println(priority.poll());
System.out.println(priority.poll());
}
}
Output:
[id:101 name:Atlas, id:101 name:Ptlas, id:101 name:Ftlas, id:102 name:Ztlas]
id:101 name:Atlas
id:101 name:Ftlas
id:101 name:Ptlas
id:102 name:Ztlas
A bit further down in the documentation it says:
The Iterator provided in method iterator() is not guaranteed to traverse the elements of the priority queue in any particular order.
Since AbstractCollection
's toString
(which PriorityQueue
inherits) returns a string in the iteration order, you get no particular order from it.