java - 数组搜索方法困惑

标签 java collections

我对 Arrays.binarySearch(Object[], Object) 感到困惑.

public class SearchObjArray {

    public  static void main(String[] args){

        String[] sa = {"one","two","three","four"};

        Arrays.sort(sa);

        for(String s : sa ){
            System.out.println(s + " ");
        }
        System.out.println("\n one = " + Arrays.binarySearch(sa,"thro"));
}
}

当程序运行时,它返回位置-4。我在书中读到,它指出,插入点表示为 (-(insertionPoint)-1)。为什么会这样呢?我无法理解这一点。

最佳答案

The insertion point is defined as the point at which the key would be inserted into the array.

{"one","two","three","four"}

排序后为

{"four", "one", "three", "two"}

throw位于之后。所以插入点是3。结果是

(-(insertionPoint) -1) =
(-(3)              -1) =
-4

关于java - 数组搜索方法困惑,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28538692/

相关文章:

java - 想要存储 HashMap 吗?

java - JViewport.setView 无法捕获的错误

java - Android 共享 Intent 不起作用

java - 如何使用 Comparable 接口(interface)比较 ArrayList 中对象的多个属性?

java - OCAJP 模拟测试

c# - 获取唯一元素

java - HashSet 问题——equals 和 hashCode with contains 的工作方式与我预期的不同

java - 迭代时删除元素。 removeIf 导致 ConcurrentModificationException

c# - 合并的 ObservableCollection

java - spring boot 中嵌入的geoserver 与hibernate/jpa 冲突