Integer comparator

Help and support on OCA OCP Java Programmer Certification Questions
1Z0-808, 1Z0-809, 1Z0-815, 1Z0-816, 1Z0-817

Moderator: admin

Post Reply
jelofka
Posts: 6
Joined: Tue Aug 30, 2016 5:47 am
Contact:

Integer comparator

Post 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.

admin
Site Admin
Posts: 10065
Joined: Fri Sep 10, 2010 9:26 pm
Contact:

Re: Integer comparator

Post 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.
If you like our products and services, please help us by posting your review here.

jelofka
Posts: 6
Joined: Tue Aug 30, 2016 5:47 am
Contact:

Re: Integer comparator

Post 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.

Post Reply

Who is online

Users browsing this forum: Baidu [Spider], Bing [Bot] and 226 guests