At line1, we have a sorted array of strings 'sa'.
//line 1: Searches the specified array (sa) for the specified object (rs) using the binary search algorithm.
Then at line2, why the overloaded version of method binarySearch() is needed which takes a Comparator as an argument?
Its the logic whoever wrote the program !! The following method is used
//line 2: Method Signature: public static <T> int binarySearch(T[] a, T key, Comparator<? super T> c)
The array to be searched is
sa
key the value to be searched for is
one
c the comparator by which array is ordered (
rs). (which is why comparator argument is used)
CompareTo comparison is based on the Unicode value of each character in the strings.
The result is a negative integer if this String object lexicographically precedes the argument string.
The result is a positive integer if this String object lexicographically follows the argument string.
The result is zero if the strings are equal; compareTo returns 0 exactly when the equals(Object) method would return true.
lexicographic ordering: If two strings are different, then either they have different characters at some index that is a valid index for both strings, or their lengths are different, or both.
Why the 'two argument' version of this method doesn't work here and gives unpredictable output?
Arrays.binarySearch is producing the right results. I do not see any un-expected results.
sa has sa[0] = four, sa[1] = one, sa[2] = three, sa[3]= two and for overloaded binarySearch method right output is produced.