我对 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/