Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
433 views
in Technique[技术] by (71.8m points)

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

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...