java - 具有内部比较器类的 PriorityQueue

标签 java comparator priority-queue

我尝试使用内部比较器类以降序实现优先级队列,但是当我打印优先级队列时,我没有得到正确的结果。当我尝试使用 Collection.sort 的相同比较器代码来实现列表排序(具有相同的值)时。我得到了正确的结果。您能解释一下吗?

//int[] nums = {50,10, 20, 30, 40};
    public static void TestComparatorcomparemethod(int[] nums){
        PriorityQueue<Integer> pq= new PriorityQueue<>(nums.length,new Comparator<Integer>(){
            @Override
            public int compare(Integer o1,Integer o2){
                int a = (int)o1;
                int b = (int)o2;
                if (a > b)
                    return -1;
                else if (a==b)
                    return 0;
                else
                    return 1;
            }
        });
        for (int node:nums){
            pq.add(node);}
        System.out.println("pq values are " + pq);
}

以上代码的答案是 pq 值为 [50, 40, 20, 10, 30]

        List<Integer> al = new ArrayList<>();
        al.add(50);
        al.add(10);
        al.add(20);
        al.add(30);
        al.add(40);
        Collections.sort(al, new Comparator<Integer>(){
            @Override
            public int compare(Integer o1,Integer o2){
                int a = (int)o1;
                int b = (int)o2;
                if (a > b)
                    return -1;
                else if (a==b)
                    return 0;
                else
                    return 1;
            }
        } );
        System.out.println("The arraylist values are: " + al);

以上代码的答案是 数组值为:[50, 40, 30, 20, 10]

最佳答案

对于优先级队列,意外的顺序 [50, 40, 20, 10, 30] 是可以的(预期)。因为迭代优先级队列并不能保证排序顺序。但如果您使用 peek/poll,您将看到返回了预期值。

来自DOCUMENTATION :

This class and its iterator implement all of the optional methods of the Collection and Iterator interfaces. The Iterator provided in method iterator() is not guaranteed to traverse the elements of the priority queue in any particular order. If you need ordered traversal, consider using Arrays.sort(pq.toArray()).

您的比较器代码没问题。如果您确实需要按顺序打印值,请尝试:

 System.out.println("pq values are " + Arrays.sort(pq.toArray());

关于java - 具有内部比较器类的 PriorityQueue,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60483724/

相关文章:

java - 如何保持 Google App Engine 的运行实例

java定时器用按钮改变延迟

java - 比较方法在排序文件时违反了它的一般契约

java - 将 Java 比较器逻辑移出实体?

c++ - 如何使优先级队列使用自定义类中的变量(升序/降序)

node.js - 如何中止公牛队列中的特定任务?

haskell - Haskell 有没有一种简单的方法来实现快速优先级队列?

java - 在 Mule 3.4 中模拟 while 循环

java - 索引帮助 Java

Java 比较器多参数