Java Arrays.binary 搜索返回错误的数据,即使数组已排序

标签 java

文档写道:“如果数组中的所有元素都小于指定的键,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/

相关文章:

java - 如何聚合来自多个服务的 JAX-RS 响应

java - 部署项目到tomcat ROOT

java - 在Java中显示二叉搜索树

java - objectinputstream.readobject() 行 : not available [local variables unavailable]

Java bug - 无法将授权添加到 HttpURLConnection set/addRequestProperty()

java - 过滤具有多个大 vector 的行

java - 如何让Jenkins使用本地用户的.m2文件夹?

java - 通知不显示

java - 如何在java中解码具有 'default'类属性的json字符串?

java - 为什么struts.xml是正确的,但是页面却是404?