优先队列的元素根据它们的自然顺序排序,或者在队列构建时提供的比较器进行排序(具体取决于使用哪个构造函数)。然而,在下面的示例中,如果一次性打印整个队列,则队列元素会以随机顺序打印。另一方面,如果我逐个获取元素,它们会按自然顺序打印。有人能解释一下这种模糊行为吗?或者我错过了什么?
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());
}
}
输出:
[id:101 name:Atlas, id:101 name:Ptlas, id:101 name:Ftlas, id:102 name:Ztlas]
id:101 名称: Atlas
id:101 名称: Ftlas
id:101 名称: Ptlas
id:102 名称: Ztlas