Java优先级队列的自定义比较器
我试图根据自定义的Java优先级队列的自定义比较器,java,comparator,priority-queue,custom-compare,Java,Comparator,Priority Queue,Custom Compare,我试图根据自定义的比较器对优先级队列进行排序,但它抛出了一个错误: 第11行:错误:找不到适合排序的方法(队列) 优先级队列用于对自定义类对象进行排序;我尝试使用不同的比较器对优先级队列进行多次排序 我试图执行的代码: class Solution { public List<Integer> findClosestElements(int[] arr, int k, int x) { // insert elements to PQ by distance
比较器对优先级队列进行排序,但它抛出了一个错误:
第11行:错误:找不到适合排序的方法(队列)
优先级队列用于对自定义类对象进行排序;我尝试使用不同的比较器对优先级队列进行多次排序
我试图执行的代码:
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;
}
}
类解决方案{
公共列表查找关闭项(int[]arr,int k,int x){
//按距离将图元插入PQ
队列pq=新的优先级队列();
对于(int i=0;ia.index-b.index);不返回可用于排序的合适方法(Queue,(a,b)->a.i[…]index)
List ret=新阵列列表(k);
while(ret.size()!=k){
ret.add(pq.poll().num);
}
返回ret;
}
}
类自定义实现Comparator,Comparable{
public int dist=0,num,index;
公共自定义(int dist、int num、int index){
this.dist=dist;
this.num=num;
这个指数=指数;
}
公共整数比较(自定义a、自定义b){
返回b.dist-a.dist;
}
公共整数比较(自定义b){
返回b.dist-this.dist;
}
}
因为sort使用的是List:,但Queue不是列表。调用sort with PriorityQueue时,您希望发生的情况可能重复?PriorityQueue是一个二进制堆(树的一种类型),因此它不能像列表或普通数组那样排序。请参见例如Sort是Collections类的静态方法。排序的第一个参数是List,但Queue不是List,所以这段代码不会编译,就这么简单。我不知道为什么我会落选。哎呀,我错了。不幸的是,除非你以某种方式改变答案,否则我不会撤消我的否决票。(我建议添加一个到Collections.sort javadoc的链接。)@vgr好的,我添加了一个链接,你能删除下一票吗?谢谢你的好意:)