Collections.binarySearch(List list, K key) clarification. Java

陌路散爱 提交于 2019-11-26 21:38:28

问题


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

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.

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

In brief: why (-(insertion point) - 1) and not only (-(insertion point))?

Thanks in advance.


回答1:


That's because -(insertion point) would be ambiguous. You wouldn't be able to tell the following apart:

  • item found at position 0;
  • item not found, and insertion point is 0.

With -(insertion point) - 1, the above two cases result in different return values (0 and -1).




回答2:


from your link

This admittedly ugly formula guarantees that the return value will be >= 0 if and only if the search key is found. It's basically a hack to combine a boolean (found) and an integer (index) into a single int return value



来源:https://stackoverflow.com/questions/15811440/collections-binarysearchlist-list-k-key-clarification-java

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!