Page 1 of 1

Integer comparator

Posted: Tue Oct 04, 2016 7:53 am
by jelofka
Hi,
am a bit confused about binarySearch on Arraylist of Integers with this desc comparator (if comparator is asc things are clear to me):

public class SortandSearch{

static final Comparator<Integer> IntegerComparator=new Comparator<Integer>(){
public int compare (Integer n1, Integer n2){
return n2.compareTo(n1);
}
};

public static void main(String[] args) {
ArrayList<Integer> list = new ArrayList<>();
list.add(4);
list.add(1);
list.add(3);
list.add(2);

Collections.sort(list,IntegerComparator);

System.out.println(Collections.binarySearch(list, 3));

}

}

It returns 1. OK.
If we do System.out.println(Collections.binarySearch(list, 2));
it returns -1. Why not 2?
If I do System.out.println(Collections.binarySearch(list, 5));
it returns -5, why not -1?

Tnx.

Re: Integer comparator

Posted: Tue Oct 04, 2016 10:44 am
by admin
Because JavaDoc for binarySearch clearly says that it expects the list to be sorted into ascending order according to the natural ordering of its elements (as by the Collections.sort(List) method) prior to making this call. If it is not sorted, the results are undefined.

The elements in your list are not sorted according to the natural ordering of its elements. So you should not be surprised by the output :)

HTH,
Paul.

Re: Integer comparator

Posted: Tue Oct 04, 2016 12:49 pm
by jelofka
I posted this question after 1,5h of research and obviously bad reading. I knew I missed something, hit dead end, so had to ask. Now I feel exactly the way I knew I was gonna feel -stupid. If only I could say it will not happen again. But sure, next time I will give it 3h before asking :)

Many thanks.