Java:优先队列

7
我可以翻译以下内容:

我有一个Java程序,代码如下:

public class 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规范,它实现了Comparable接口并维护排序顺序(自然排序)。

我的程序输出如下:[1, 2, 3, 4, 5, 9, 7, 10, 6, 8]

3个回答

7

将元素插入优先队列并不足以对元素列表进行排序,因为它不会将它们存储在排序顺序中;它将它们存储在部分排序的堆顺序中。你需要循环删除元素来对它们进行排序:

while (pq.size() > 0)
    System.out.println(pq.remove());

7

队列已排序,但内部元素存储在堆中。如果调用 peek()poll()remove(),您将获得正确的顺序(这就是访问队列的方式)。


0

根据Java8的规定,poll()和remove()会按排序顺序返回值,而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
1

代码示例在这里更需要。请将其添加到上下文中。 - ZF007

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