java - binarySearch collections using ArrayList -


i'm sorry stupid question, have been searching how use binarysearch arraylist :

list<integer> arrlist = new arraylist<integer>();                arrlist.add(3);          arrlist.add(5);          arrlist.add(7);         arrlist.add(2); 

the problem when use :

collections.sort(arrlist); collections.reverse(arrlist); int indeks = collections.binarysearch(arrlist, 7); 

the value of indeks -5, thought should 2 because after reversing myarrlist output looks :

[7, 5, 3, 2] 

so should here in order right indeks of 7...? in advance

collections.binarysearch() expects elements in ascending order:

the list must sorted ascending order according natural ordering of elements (as sort(list) method) prior making call. if not sorted, results undefined.

if want binary search on descending list, use comparator.reverseorder():

int indeks = collections.binarysearch(arrlist, 7, comparator.reverseorder()); 

indeks 0, corresponding first element of list.

note can use same comparator sort list descending, instead of sorting ascending , reversing:

collections.sort(arrlist, comparator.reverseorder());