Janusz Chudzynski
Janusz Chudzynski

Reputation: 2710

IMplementing custom comparator

I am trying to implement a custom comparator for Beacon class (AltBeacon) framework.

      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;
       }
   });

It fails with a following error:

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>)

Upvotes: 0

Views: 177

Answers (1)

xorgate
xorgate

Reputation: 2264

Collections.sort() sorts the list inplace.

What you are doing is passing it a new List, but after the call it's not available to you anymore, so it's useless.

Put the beacons in a List first, then sort it, then use the sorted List.

Upvotes: 1

Related Questions