Here is the simple piece of code that I build to understand Arrays.binarySearch. But it is returning a result which I did not even expect.
String[] c = {"A", "Z", "B"};
Arrays.sort(c, new MyNewComparator1()); //Z, B, A
System.out.println(Arrays.binarySearch(c, "Z")); //0
System.out.println(Arrays.binarySearch(c, "S")); //-2 based on insertion point
System.out.println(Arrays.binarySearch(c, "N")); //Unpredicable result we can expect
Here is my custom Comparator
class MyNewComparator1 implements Comparator<String> {
public int compare(String s1, String s2) {
return s2.compareTo(s1);
}
}
Result I am expecting 0, -2, Unpredictable
But the result it is returning -4, -4, -4
Can someone please help me to understand why it is returning -4 for all the search?
Thanks
Comparatoryou've used to sort your list. Try using the overload withArrays.binarySearch(T[], T, Comparator<T>). Returns the results you expect (although I think"N"would just return-2as well...).