我有一个java程序,它是这样的。
公共类PriorityQueueExample {
public static void main(String[] args) {
PriorityQueue<Integer> pq = new PriorityQueue<Integer>();
pq.add(10);
pq.add(1);
pq.add(9);
pq.add(2);
pq.add(8);
pq.add(3);
pq.add(7);
pq.add(4);
pq.add(6);
pq.add(5);
System.out.println(pq);
}}
我的问题是,为什么优先级队列不对它们进行排序。根据java规范,它实现了可比较的,并保持了排序顺序(自然排序)。
我的程序输出如下: 1,2,3,4,5,9,7,10,6,8
发布于 2011-10-28 17:09:56
插入到优先级队列中不足以对元素列表进行排序,因为它不按排序顺序存储元素;它以部分排序的堆顺序存储元素。您必须删除循环中的元素才能对它们进行排序:
while (pq.size() > 0)
System.out.println(pq.remove());发布于 2011-10-28 17:11:04
它是经过排序的,但在内部,元素存储在堆中。如果调用peek()、poll()或remove(),就会得到正确的顺序(这就是访问队列的方式)。
发布于 2019-11-28 00:47:22
poll()和remove()将按照java8给出排序顺序,而不是peek()。
PriorityQueue<Integer> pq = new PriorityQueue<Integer>();
pq.add(10);
pq.add(1);
pq.add(9);
pq.add(2);
pq.add(8);
pq.add(3);
pq.add(7);
pq.add(4);
pq.add(6);
pq.add(5);
// Remove items from the Priority Queue (DEQUEUE)
while (!pq.isEmpty()) {
// System.out.println(pq.remove());
System.out.println(pq.poll());
}
Output for poll() & remove():
1
2
3
4
5
6
7
8
9
10
output for peek():
1
1
1
1
1
1
1
1
1
1https://stackoverflow.com/questions/7927213
复制相似问题