首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >Java优先级队列的自定义比较器

Java优先级队列的自定义比较器
EN

Stack Overflow用户
提问于 2018-08-05 06:46:55
回答 1查看 885关注 0票数 0

我正在尝试根据自定义Comparators对优先级队列进行排序,但它抛出了一个错误:

代码语言:javascript
复制
Line 11: error: no suitable method found for sort(Queue<Custom>,<anonymous Comparator<Custom>>)

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

我尝试执行的代码如下:

代码语言:javascript
复制
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;
        }
    }
EN

回答 1

Stack Overflow用户

发布于 2018-08-05 06:58:23

因为排序使用的是List:sort(List list, Comparator c),但队列不是列表。

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/51690097

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档