【问题标题】:Java priority queue oderJava 优先队列顺序
【发布时间】:2015-04-27 18:22:09
【问题描述】:

导入 java.util.Comparator; 导入 java.util.PriorityQueue;

公共类 minMaxHeap {

    static class PQsort implements Comparator<Integer> {

        public int compare(Integer one, Integer two) {
            return two - one;
        }
    }

    public static void main(String[] args) {
        int[] ia = { 1, 10, 5, 3, 4, 7, 6, 9, 8 };
        PriorityQueue<Integer> pq1 = new PriorityQueue<Integer>();

        // use offer() method to add elements to the PriorityQueue pq1
        for (int x : ia) {
            pq1.offer(x);
        }
        for(int num : pq1){
            System.out.print(" " + num);
        }
        System.out.println("");

        PQsort pqs = new PQsort();
        PriorityQueue<Integer> pq2 = new PriorityQueue<Integer>(10, pqs);
        // In this particular case, we can simply use Collections.reverseOrder()
        // instead of self-defined comparator
        for (int x : ia) {
            pq2.offer(x);
        }

        for(int num : pq2){
            System.out.print(" " + num);
        }



    }

}

我有这样的代码。 在 java 中,我使用优先级队列来存储值数组。 当我尝试将它们一张一张打印出来时,我希望看到它们是按顺序打印的。如:1 3 4 5 6 7 8 9。 但是为什么我看到“1 3 5 8 4 7 6 10 9”?

当我通过提供另一个比较器来使用 reversedOrder 时。 结果也很奇怪,就是 “10 9 7 8 4 5 1 4” 这是为什么呢?

谢谢

【问题讨论】:

  • 你的比较器是什么?
  • @CPerkins 抱歉。更正了我的代码。之前复制了错误的代码。
  • @BufBills 请修正格式。

标签: java


【解决方案1】:

PriorityQueue 不能替代已排序的集合!它只是保证,元素的重复出队(通过poll())会根据它们的优先级删除它们,但在内部,元素不需要以完全排序的顺序存储。

PriorityQueue的JavaDoc:

方法 iterator() 中提供的迭代器不能保证 以任何特定顺序遍历优先级队列的元素。 如果您需要有序遍历,请考虑使用 Arrays.sort(pq.toArray()).

PriorityQueue#iterator()的JavaDoc:

返回此队列中元素的迭代器。迭代器确实 不按任何特定顺序返回元素。

阅读文档通常不会受到伤害!

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-09-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-03-24
    • 1970-01-01
    • 1970-01-01
    • 2021-11-29
    相关资源
    最近更新 更多