gpt4 book ai didi

java - 实现自定义比较器

转载 作者:行者123 更新时间:2023-12-01 09:36:42 27 4
gpt4 key购买 nike

我正在尝试为 Beacon 类 (AltBeacon) 框架实现一个自定义比较器。

      Collections.sort(Arrays.asList(beacons), new Comparator<Beacon>(){
@Override
public int compare(Beacon lhs, Beacon rhs) {
double diff = lhs.getDistance() - rhs.getDistance();

if (diff > 0 ){
return 1;
}

if (diff < 0 ){
return -1;
}


return 0;
}
});

失败并出现以下错误:

Error:(176, 19) error: no suitable method found for sort(List<Collection<Beacon>>,<anonymous Comparator<Beacon>>) method Collections.<T#1>sort(List<T#1>) is not applicable (cannot infer type-variable(s) T#1 (actual and formal argument lists differ in length)) method Collections.<T#2>sort(List<T#2>,Comparator<? super T#2>) is not applicable (inferred type does not conform to upper bound(s) inferred: Collection<Beacon> upper bound(s): Beacon,Object) where T#1,T#2 are type-variables: T#1 extends Comparable<? super T#1> declared in method <T#1>sort(List<T#1>) T#2 extends Object declared in method <T#2>sort(List<T#2>,Comparator<? super T#2>)

最佳答案

Collections.sort() 对列表进行就地排序。

你正在做的是向它传递一个新的列表,但是在调用之后它不再可供你使用,所以它没有用。

先将信标放入List中,然后对其进行排序,然后使用排序后的List。

关于java - 实现自定义比较器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38836852/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com