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

binary-search, java, return

Solution

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

Problem

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.

Original source