优先队列是否维护自然顺序?

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

1个回答

3
在文档的稍下方,有这样一句话:文档中写道:
迭代器提供的iterator()方法不能保证以任何特定顺序遍历优先级队列的元素。
由于AbstractCollection的toString(PriorityQueue继承)返回按迭代顺序排序的字符串,因此您无法从中得到任何特定顺序。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接