当元素不存在且-insertion_point不存在时,为什么Collections.binarySearch返回-(insertion_point-1)? [英] Why is -(insertion_point - 1) returned by Collections.binarySearch when an element not present and not -insertion_point?

查看:107
本文介绍了当元素不存在且-insertion_point不存在时,为什么Collections.binarySearch返回-(insertion_point-1)?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

曾经使用BinarySearch方法,想知道为什么当元素不存在且-insertion_point不存在时,Collections.binarySearch返回-(insertion_point-1)吗?我知道为什么它是负数,但是为什么是-1?

Been using the binarySearch method and wondering why is -(insertion_point - 1) returned by Collections.binarySearch when an element not present and not -insertion_point? I understand why it is negative, but why the -1?

推荐答案

因为您不能使用负0.

考虑是否存在 -1 的情况.如果在索引0处找到一个元素,则它将返回0.如果未找到某个元素,但其插入点为0,则它​​也将返回零.您如何区分这两种情况?加上 -1 ,现在它们分别返回 0 -1 ,让您与众不同.

Consider the situation if there was no -1. If an element was found at index 0, it would return 0. If an element was not found, but it's insertion point was 0, it too would return zero. How could you distinguish between these two situations? With the addition of the -1, now they return 0 and -1 respectively, letting you distinguish.

它是-(插入点)-1 ,与您的问题所陈述的内容略有不同.

And it is -(insertion point) - 1 which is slightly different than what your question states.

这篇关于当元素不存在且-insertion_point不存在时,为什么Collections.binarySearch返回-(insertion_point-1)?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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