队列没有自然排序

可能重复:
为什么这个奇怪的顺序发生在java的PriorityQueue中?

请看下面的代码:

public static void main(String[] args) { Queue q = new PriorityQueue(); q.offer("car"); q.offer("airplane"); q.offer("bicycle"); Iterator i = q.iterator(); while(i.hasNext()) System.out.print(i.next() + " "); } 

有人可以解释为什么输出

 airplane car bicycle 

代替

 airplane bicycle car 

因为在API中它表示优先级队列的元素是按照它们的自然顺序排序的。

PriorityQueue基于优先级堆。 尽管元素未排序,但此数据结构允许非常快速地检索最少元素。 向PriorityQueue添加元素比基于树的TreeSet更快。 由于元素没有排序,因此API所说的迭代器“不会以任何特定的顺序返回元素”。

根据迭代器的javadoc :

迭代器不会以任何特定顺序返回元素。

但是,第一项(头部)保证是最小的。 所以这应该打印你期望的:

 public static void main(String[] args) throws Exception { Queue q = new PriorityQueue(); q.offer("car"); q.offer("airplane"); q.offer("bicycle"); String e = null; while ((e = q.poll()) != null) { System.out.println(e); } } 

如果要对迭代进行排序,则需要使用不同的结构,例如,如果没有重复项,则使用TreeSet