Why does it always return 49999 no matter what strToSearch variable holds? Even with the clank search variable it returns the same. Have I missed something:
String[] arr = new String[100000];
String strToSearch = "12";
for (int i = 0; i < arr.length; i++) {
arr[i] = i+","+i;
}
Arrays.sort(arr, new Comparator<String>() {
@Override
public int compare(String o1, String o2) {
if(o1 != null && o2 != null && !o1.isEmpty() && !o2.isEmpty() && o1.indexOf(",") != -1 && o2.indexOf(",") != -1) {
String[] o1Arr = o1.split(",");
String[] o2Arr = o2.split(",");
Integer one = Integer.parseInt(o1Arr[0]);
Integer two = Integer.parseInt(o2Arr[0]);
return one.compareTo(two);
}
return 0;
}
});
System.out.println(Arrays.binarySearch(arr, strToSearch, new Comparator<String>() {
@Override
public int compare(String o1, String o2) {
if(o1 != null && o2 != null && !o1.isEmpty() && !o2.isEmpty() && o1.indexOf(",") != -1 && o2.indexOf(",") != -1) {
String[] o1Arr = o1.split(",");
String[] o2Arr = o2.split(",");
return o1Arr[0].compareTo(o2Arr[0]);
}
return 0;
}
}));
My array contains comma separated values and I want to search based on string before comma in array elements. Is there any other simple solution available? I have also made a custom method which loops over array and finds the string but I’m looking for some alternatives.
The JavaDoc on
Arrays.binarySearch(...)states that the array must already be sorted and thus the comparator actually compares the array value and the search string and not is not used for sorting the array again.This means you get something like
compare(arr[x], "12")and your if condition states that both strings must contain a comma, otherwise they are equal. And"12"doesn’t contain any commas, thus making"12"equal to every element in the array (always returns 0).Edit:
Looking at the source code seems to support my assumption.
There’s this line, for example:
The reason for 49999 being returned is that the first
midvalue is at indexmid = (low + high) >> 1which is(0 + 99999) >> 1 == 49999and since the comparator returns 0 the values are considered equal. And boom, the value is “found”.