Collections.binarySearch(List list, K key) clarification. Java(Collections.binarySearch(List list, K key) 澄清.爪哇)
问题描述
鉴于以下陈述,取自 thisOracle java教程,涉及Collections类的binarySearch()方法:
Given the following statement, taken from this Oracle java tutorial, related to the binarySearch() method of the class Collections:
两种形式的返回值相同.如果列表包含搜索键,返回其索引.如果不是,则返回值为(-(insertion point) - 1),其中插入点是在该值将被插入到列表中,或者是第一个元素大于值或 list.size() 如果所有元素都在列表小于指定值.
The return value is the same for both forms. If the List contains the search key, its index is returned. If not, the return value is (-(insertion point) - 1), where the insertion point is the point at which the value would be inserted into the List, or the index of the first element greater than the value or list.size() if all elements in the List are less than the specified value.
为什么binarySearch()
的返回值不是只返回负数,而是负数减1?(上面引用的粗体部分).
Why does the return value of binarySearch()
not return only the negative index instead of the negative index minus 1? (the part in bold of the quote above mentioned).
简而言之:为什么是 (-(insertion point) - 1)
而不仅仅是 (-(insertion point))
?
In brief: why (-(insertion point) - 1)
and not only (-(insertion point))
?
提前致谢.
推荐答案
那是因为 -(insertion point)
会模棱两可.您将无法区分以下内容:
That's because -(insertion point)
would be ambiguous. You wouldn't be able to tell the following apart:
- 在
0
位置找到项目; - 找不到项目,插入点是
0
.
- item found at position
0
; - item not found, and insertion point is
0
.
使用-(插入点)-1
,以上两种情况导致返回值不同(0
和-1
).
With -(insertion point) - 1
, the above two cases result in different return values (0
and -1
).
这篇关于Collections.binarySearch(List list, K key) 澄清.爪哇的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:Collections.binarySearch(List list, K key) 澄清.爪哇
基础教程推荐
- 设置 bean 时出现 Nullpointerexception 2022-01-01
- 如何使用 Java 创建 X509 证书? 2022-01-01
- 减少 JVM 暂停时间 >1 秒使用 UseConcMarkSweepGC 2022-01-01
- Java:带有char数组的println给出乱码 2022-01-01
- 在 Libgdx 中处理屏幕的正确方法 2022-01-01
- FirebaseListAdapter 不推送聊天应用程序的单个项目 - Firebase-Ui 3.1 2022-01-01
- “未找到匹配项"使用 matcher 的 group 方法时 2022-01-01
- 降序排序:Java Map 2022-01-01
- Java Keytool 导入证书后出错,"keytool error: java.io.FileNotFoundException &拒绝访问" 2022-01-01
- 无法使用修饰符“public final"访问 java.util.Ha 2022-01-01