Пользовательский компаратор очереди приоритетов Java
Я пытаюсь отсортировать приоритетную очередь на основе пользовательских 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;
}
}
1 ответ
Потому что сортировка работает со списком: sort(List<T> list, Comparator<? super T> c)
, но очередь не является списком.