PriorityQueue 是否保持自然顺序?
Does PriorityQueue maintain natural order?
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
在 the documentation 再往下说:
The Iterator provided in method iterator() is not guaranteed to traverse the elements of the priority queue in any particular order.
由于 AbstractCollection
的 toString
(PriorityQueue
继承)returns 迭代顺序中的一个字符串,您不会从中得到特定的顺序。
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
在 the documentation 再往下说:
The Iterator provided in method iterator() is not guaranteed to traverse the elements of the priority queue in any particular order.
由于 AbstractCollection
的 toString
(PriorityQueue
继承)returns 迭代顺序中的一个字符串,您不会从中得到特定的顺序。