可能重复: 为什么在Java中的PriorityQueue中会发生这种奇怪的顺序?/a>
Possible Duplicate: Why is this strange order happens in PriorityQueue in java?
请参见下面的代码:
public static void main(String[] args) { Queue<String> q = new PriorityQueue<String>(); q.offer("car"); q.offer("airplane"); q.offer("bicycle"); Iterator<String> i = q.iterator(); while(i.hasNext()) System.out.print(i.next() + " "); }有人可以解释一下为什么输出
Can someone explain me why the output is
airplane car bicycle代替
airplane bicycle car?
自在API中以来,表示优先级队列的元素是根据其自然顺序进行排序的.
Since in the API it says that the elements of the priority queue are ordered according to their natural ordering.
推荐答案PriorityQueue基于优先级堆.尽管未对元素进行排序,但此数据结构允许非常快地检索最小元素.将元素添加到PriorityQueue的速度比添加到基于树的TreeSet的速度快.由于未对元素进行排序,因此如API所述,迭代器不会以任何特定顺序返回元素".
PriorityQueue is based on a priority heap. This data structure allows to retrieve the least element very quickly though the elements are not sorted. Adding elements to PriorityQueue is faster than to TreeSet which is tree based. Since the elements are not sorted, the iterator, as API says, "does not return the elements in any particular order".
更多推荐
队列不自然排序
发布评论