Searching in an array with custom comparator in java

前端 未结 4 1738
醉酒成梦
醉酒成梦 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: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() {
        @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;
        }
    }));
    

提交回复
热议问题