Code: Select all
class MyStringComparator implements Comparator
{
public int compare(Object o1, Object o2)
{
int s1 = ((String) o1).length();
int s2 = ((String) o2).length();
return s1 - s2;
}
}
and
static String[] sa = { "d", "bbb", "aaaa" };
Arrays.binarySearch(sa, "cc", new MyStringComparator()); will return -2.
Since there is no string of length 2 in sa, nothing in sa matches aa. So the return value has to be negative. Further, if aa were to be inserted in sa, it would have to be inserted after 'a' i.e. at index 1. Thus, the return value will be -(index+1) = -2.
I am confused. Where is "aa" mentioned in the code for this question, or are you referring to "cc" which is what is stated in this answer selection?....nothing in sa matches aa....Further, if aa were to be inserted....