Searching in an array with custom comparator in java

前端 未结 4 1697
醉酒成梦
醉酒成梦 2021-01-17 00:58

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 s

相关标签:
4条回答
  • 2021-01-17 01:13

    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:

     //c is the Comparator
     //midVal is an element of your array 
     //key is the key parameter you passed to binarySearch(...)
     c.compare(midVal, key); 
    

    The reason for 49999 being returned is that the first mid value is at index mid = (low + high) >> 1 which is (0 + 99999) >> 1 == 49999 and since the comparator returns 0 the values are considered equal. And boom, the value is "found".

    0 讨论(0)
  • 2021-01-17 01:20

    In your 2nd if-Statement: since your strToSearch = "12" and do not contain a ",", the

    o2.indexOf(",") != -1
    

    will always return false.

    Delete the hole if-Statement or at least the last part and it works.

    0 讨论(0)
  • 2021-01-17 01:22

    Problem is in your binarysearch's comparator method. It should be re-written like this:

    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) {
                String[] o1Arr = o1.split(",");
                int i1 = Integer.parseInt(o2);
                int i2 = Integer.parseInt(o1Arr[0]);
                return i2-i1;
            }
            return 0;
        }
    }));
    
    0 讨论(0)
  • 2021-01-17 01:24

    You assume that String strToSearch is of type "12,12". To make this code work just change strToSearch

    For example:

    Arrays.binarySearch(arr, "12,12", new Comparator<String>)
    
    0 讨论(0)
提交回复
热议问题