为什么 java Arrays.binarySearch return (-(插入点) - 1) 找不到时

Why java Arrays.binarySearch return (-(insertion point) - 1) when not found

我目前正在尝试学习 java Arrays.binarySearch,并查看下面的 Oracle 文档:

Arrays.binarySearch(int[] a, int fromIndex, int toIndex, int key)

Returns:

index of the search key, if it is contained in the array within the specified range; otherwise, (-(insertion point) - 1)**

找不到的时候,不知道为什么return-(插入点)-1在这里?为什么不只是 return -1 或 -(插入点)? -(插入点) - 1 的想法是什么?

因为它提供了在其他情况下无法获得的额外信息。因此它需要插入点来传达该信息。问题是,插入点可能为 0。那么如何区分 0 匹配和插入点 0 失败呢?您必须 -1 才能进行区分。