IMplementing自定义比较器

时间:2016-08-08 19:12:18

标签: java sorting

我正在尝试为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>)

1 个答案:

答案 0 :(得分:1)

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

你正在做的是传递一个新的列表,但在通话后它再也无法使用,所以它没用。

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