java PriorityQueue维护自然秩序吗?
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.
但是,在下面的示例中,当我一次打印整个队列时,队列的元素以随机顺序打印。另一方面,如果我逐个轮询元素,它们将按自然顺序打印
有人能给我解释一下这种模棱两可的行为吗?还是我遗漏了什么强>
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 name:Atlas
id:101 name:Ftlas
id:101 name:Ptlas
id:102 name:Ztlas
# 1 楼答案
再往下一点the documentation它说:
由于
AbstractCollection
的toString
(由PriorityQueue
继承)以迭代顺序返回字符串,因此不会从中获得特定顺序