【问题标题】:Custom comparator of Java priority queueJava优先级队列的自定义比较器
【发布时间】:2018-08-04 22:46:54
【问题描述】:

我正在尝试根据自定义 Comparators 对优先级队列进行排序,但它会引发错误:

Line 11: error: no suitable method found for sort(Queue<Custom>,<anonymous Comparator<Custom>>)

优先级队列用于对自定义类对象进行排序;我正在尝试使用不同的比较器对优先级队列进行多次排序。

我试图执行的代码:

class Solution {
    public List<Integer> findClosestElements(int[] arr, int k, int x) {
        // insert elements to PQ by distance
        Queue<Custom> pq = new PriorityQueue<Custom>();
        for(int i=0; i< arr.length; i++){
            // should sort the elements by default compare method of custom class
            pq.offer(new Custom(Math.abs(x-arr[i]), arr[i], i));
        }
        // some operations
        Collections.sort(pq, new Comparator<Custom>(){
            public int compare(Custom a, Custom b){
                return a.index-b.index;
            }
         });
        // using the lambda just like Collections.sort(pq, (a,b) -> a.index-b.index); returns no suitable method available for sort(Queue<Custom>,(a,b)->a.i[...]index)
        List<Integer> ret = new ArrayList<Integer>(k);
        while(ret.size()!=k){
            ret.add(pq.poll().num);
        }
        return ret;
    }
}
class Custom implements Comparator<Custom>, Comparable<Custom>{
        public int dist=0, num, index;
        public Custom(int dist, int num, int index){
            this.dist = dist;
            this.num = num;
            this.index = index;
        } 
        public int compare(Custom a, Custom b){
            return b.dist-a.dist;
        }
        public int compareTo(Custom b){
            return b.dist-this.dist;
        }
    }

【问题讨论】:

标签: java comparator priority-queue custom-compare


【解决方案1】:

因为 sort 使用 List:sort(List&lt;T&gt; list, Comparator&lt;? super T&gt; c),但 Queue 不是 List。

【讨论】:

  • Sort 是 Collections 类的静态方法。排序的第一个参数是 List,但是 Queue 不是一个列表,所以这段代码没有编译,就这么简单。不知道为什么我会被否决。
  • 糟糕,我的错误。不幸的是,除非您以某种方式更改答案,否则 SO 不会让我撤消我的反对票。 (我建议添加一个指向 Collections.sort javadoc 的链接。)
  • @vgr 好的,我添加了一个链接,你能删除反对票吗?谢谢你的好意:)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-04-15
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多