【问题标题】:Java : Priority QueueJava:优先队列
【发布时间】:2011-10-28 09:06:40
【问题描述】:

我有一个类似这样的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]

【问题讨论】:

    标签: java collections priority-queue


    【解决方案1】:

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

    【讨论】:

      【解决方案2】:

      插入优先级队列不足以对元素列表进行排序,因为它不会按排序顺序存储它们;它将它们存储在部分排序的堆顺序中。您必须删除循环中的元素才能对它们进行排序:

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

      【讨论】:

        【解决方案3】:

        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
        1
        

        【讨论】:

        • 这里更需要代码示例。请在上下文中添加它。 (低质量审查结束)。
        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多