0

I am trying to sort a priority queue based on custom Comparators but it throws an error:

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

The priority queue is used to sort a custom class object; I am trying to sort the priority queue multiple times using different comparators.

The code I was trying to execute:

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;
        }
    }
Ivar
  • 6,138
  • 12
  • 49
  • 61
RobinHood
  • 33
  • 1
  • 8
  • Possible duplicate of [How do I use a PriorityQueue?](https://stackoverflow.com/questions/683041/how-do-i-use-a-priorityqueue) – Ivar Aug 04 '18 at 22:55
  • 1
    What do you want to happen when you call sort with a PriorityQueue? A PriorityQueue is a binary heap (a type of tree), so it can't be sorted like a list or plain array. See e.g. https://stackoverflow.com/q/25569625/2891664 – Radiodef Aug 04 '18 at 23:47

1 Answers1

0

Because sort is working with List: sort(List<T> list, Comparator<? super T> c), but Queue is not a List.

Mike
  • 812
  • 9
  • 25
  • Sort is static method of Collections class. First parameter to sort is List, but Queue is not a list, so this code doesn't compile, as simple as that. Don't know why did I get downvotes. – Mike Aug 05 '18 at 07:42
  • Oops, my mistake. Unfortunately SO won’t let me undo my downvote unless you change the answer in some way. (I suggest adding a link to the Collections.sort javadoc.) – VGR Aug 05 '18 at 09:56
  • @vgr ok, I've added a link, can you remove the downvote? Thank you for your kindness :) – Mike Aug 05 '18 at 15:29