Collections.binarySearch(列表,K键)澄清。 Java的 [英] Collections.binarySearch(List list, K key) clarification. Java

查看:146
本文介绍了Collections.binarySearch(列表,K键)澄清。 Java的的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

Given the following statement, taken from this Oracle java tutorial, related to the binarySearch() method of the class Collections:


两个表单的返回值相同。如果List包含
搜索键,则返回其索引。如果没有,则返回值为
( - (插入点) - 1),其中插入点是
处的值,该值将插入到List中,或
第一个元素的索引大于值或list.size()如果List中
中的所有元素都小于指定值。

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

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

In brief: why (-(insertion point) - 1) and not only (-(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(列表,K键)澄清。 Java的的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆