Collections.binarySearch(列表,K键)澄清. Java的

鉴于以下声明,取自 this Oracle java教程,与类Collections的binarySearch()方法有关:

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? (上面引用的粗体部分).

简而言之:为什么( – (插入点) – 1)而不仅仅是( – (插入点))?

提前致谢.

解决方法

那是因为 – (插入点)不明确.您将无法区分以下内容

>在0位找到的项目;
>找不到项目,插入点为0.

使用 – (插入点) – 1时,上述两种情况会导致不同的返回值(0和-1).

相关文章

最近看了一下学习资料,感觉进制转换其实还是挺有意思的,尤...
/*HashSet 基本操作 * --set:元素是无序的,存入和取出顺序不...
/*list 基本操作 * * List a=new List(); * 增 * a.add(inde...
/* * 内部类 * */ 1 class OutClass{ 2 //定义外部类的成员变...
集合的操作Iterator、Collection、Set和HashSet关系Iterator...
接口中常量的修饰关键字:public,static,final(常量)函数...