文档写道:“如果数组中的所有元素都小于指定的键,Arrays.binarySearch 将返回 a.length。”所以在下面的程序中,我希望打印值 4,但它打印了 -4。为什么会出现这种异常行为?
import java.io.*;
import java.math.*;
import java.util.*;
import java.lang.*;
public class Main{
public static void main(String[] args)throws java.lang.Exception{
int[] a = new int[3];
a[0] = 3;
a[1] = 8;
a[2] = 9;
System.out.println(Arrays.binarySearch(a, 15));
}
}
最佳答案
引自Java Docs ..
Returns: index of the search key, if it is contained in the array; otherwise, (-(insertion point) - 1).
插入点在哪里
defined as the point at which the key would be inserted into the array: the index of the first element greater than the key, or a.length if all elements in the array are less than the specified key
在您的示例中,所有元素都小于 15
,并且数组的长度为 3
。所以插入点是 3
,因此 binarySearch 返回 -3-1 = -4
。
关于Java Arrays.binary 搜索返回错误的数据,即使数组已排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19342502/