在Java中的PriorityQueue中的奇怪排序 [英] Strange ordering in PriorityQueue in Java
问题描述
我试图使用优先级队列来保持整数的有序列表。 in a simple exaple like this:
I am trying to use priority queue to keep an ordered list of integers. in a simple exaple like this:
PriorityQueue<Integer> queue = new PriorityQueue<>();
queue.offer(3000);
queue.offer(1999);
queue.offer(999);
for(Integer i : queue)
System.out.println(i);
打印
999
3000
1999
我期待考虑自然odering。
This is not what I am expecting considering natural odering.
我只想迭代,而不通过队列(作为排序列表)进行删除或添加。
I simply want to iterate without removing or adding through the queue (which serves as a sorted list) WITH ordering. Can I still do that in a simple manner?
推荐答案
PriorityQueue是一个优化的集合,可快速查找尾部或头部值,一个称为堆的部分有序树结构(在维基百科上查找)。如果弹出元素,它们将被排序。如果你想迭代,使用例如SortedSet代替,它也存储元素排序。
PriorityQueue is a collection optimized for finding the tail or head value quickly, using a partially ordered tree structure called heap (look it up on wikipedia). If you pop the elements, they will be ordered. If you want to iterate, use for example a SortedSet instead, which also stores the elements sorted.
这篇关于在Java中的PriorityQueue中的奇怪排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!