首页 > 解决方案 > Why the Output of Arrays.binarySearch(arr, "b") is -1. Please clarify

问题描述

import java.util.Arrays;
import java.util.Comparator;

public class MainClass {
    public static void main(String args[]) {

        String[] arr = { "c", "d", "b", "a", "e" };

        InnerClass in = new InnerClass();
        Arrays.sort(arr, in);

        for (String str : arr) {
            System.out.print(str + " ");
        }
        System.out.println(Arrays.binarySearch(arr, "b"));
    }

    static class InnerClass implements Comparator<String> {

        public int compare(String s1, String s2) {
            return s2.compareTo(s1);

        }
    }
}

Output e d c b a -1

for information if we replace Arrays.binarySearch(arr, "b") to Arrays.binarySearch(arr, "e") the output is Output e d c b a -6

标签: javaarrays

解决方案


Your array isn't sorted.

binarySearch only works on a sorted array:

The array must be sorted into ascending order according to the natural ordering of its elements (as by the sort(Object[]) method) prior to making this call. If it is not sorted, the results are undefined.


推荐阅读