java - Arrays.binarySearch 的行为

标签 java arrays binary-search

我的意图是在循环遍历 excel 文件时跳过一些预定义的行,如下所示:

int rowIndex = 0;
int[] rowsToBeSkipped = new int[]{1,2,15,16,17,18,31,32,33,34};

while (rowIterator.hasNext()) 
{
    Row row = rowIterator.next();
    if(Arrays.binarySearch(rowsToBeSkipped, rowIndex) == -1){
        System.out.println("true "+rowIndex);
    }else{
        System.out.println("false "+rowIndex);
    }
        rowIndex++;
    }
}

下面是结果:

true 0
false 1
false 2
false 3
false 4
false 5
false 6
false 7
false 8
false 9
false 10
false 11
false 12
false 13
false 14
false 15
false 16
false 17
false 18
false 19
false 20
false 21
false 22
false 23
false 24
false 25
false 26
false 27
false 28
false 29
false 30
false 31
false 32
false 33
false 34
false 35
false 36
false 37
false 38
false 39
false 40
false 41

谁能解释一下为什么只有0可以匹配条件?

最佳答案

你在滥用这个方法。引用它的文档(强调我的):

Returns: index of the search key, if it is contained in the array; otherwise, (-(insertion point) - 1). The insertion point is defined as the point at which the key would be inserted into the array

这意味着当且仅当您尝试搜索的值将被插入到数组的开头时,此方法才会返回 -1——这里是 0 的情况。

您应该测试任何严格小于 0 的值,而不仅仅是 -1:

if (Arrays.binarySearch(rowsToBeSkipped, rowIndex) < 0) {
    // etc

关于java - Arrays.binarySearch 的行为,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31157151/

相关文章:

java - 无法从静态上下文引用非静态方法 "getActivity"

java - hibernate 搜索 : what is the purpose of static block calling Version#touch()

c - 使用 glib-library 的 GArray 替换给定索引的值

javascript - 如何根据多个数组的匹配创建一个对象

arrays - 访问散列数组的更优雅的方式

c++ - 字符串数组的二进制搜索和额外功能

c - 尝试用C语言编写单词搜索程序

java - Reverse 方法反转队列的元素

java - jackson 错误意外字符 ('}'(代码 125))

arrays - 二进制搜索 "dictionary"(二维数组)