微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

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).

原文地址:https://www.jb51.cc/java/127354.html

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐