>>1."什么意思-6ren"> >>1."什么意思-在java字符串source code , 很少有地方用以下注释注明: // Note: offset or count might be near -1>>>1. 考虑以下示例: public St-6ren">
gpt4 book ai didi

java - "offset or count might be near -1>>>1."什么意思

转载 作者:IT老高 更新时间:2023-10-28 21:00:22 27 4
gpt4 key购买 nike

在java字符串source code , 很少有地方用以下注释注明:

// Note: offset or count might be near -1>>>1.

考虑以下示例:

public String(char value[], int offset, int count) {
if (offset < 0) {
throw new StringIndexOutOfBoundsException(offset);
}
if (count < 0) {
throw new StringIndexOutOfBoundsException(count);
}
// Note: offset or count might be near -1>>>1.
if (offset > value.length - count) {
throw new StringIndexOutOfBoundsException(offset + count);
}
this.offset = 0;
this.count = count;
this.value = Arrays.copyOfRange(value, offset, offset+count);
}

我们可以看到,offsetvalue.lengthcount都是int,因此值可能是 -1、0、1 或任何其他整数。评论中的“near”和“>>>”是什么意思,我这里有什么遗漏吗?

最佳答案

-1>>>1 == 2147483647是最大值 int你可以在 Java 中拥有的值(value)。

换句话说,-1>>>1 == Integer.MAX_VALUE .当您使用接近此类限制的值进行数学运算时,您获得意外结果的机会就会增加。例如,int a = (-1>>>1); System.out.println(a < a + 1);打印 false由于整数溢出,尽管人们可以预期该代码总是打印true因为,在纯数学中,对于任何整数 n确实n < n + 1 .

那段代码的作者只是在解释他(明智的)写作决定

if (offset > value.length - count)

而不是相似但不等效的

if (offset + count > value.length)

最后一个版本可能会导致整数溢出,这对后面的代码来说可能是个大麻烦。他警告说,offset 中的至少一个可能是或 count可能是接近 Integer.MAX_VALUE 的值,这增加了溢出的可能性。

对于第一个版本(您提到的 String 的源代码中使用的版本),永远不会发生溢出:您肯定知道 offsetcount由于先前的检查而为正或 0,并且 value.length也是正数或0,因为Java中数组的长度总是正数或0,所以不会发生溢出问题!

除了记录选择之外,作者还警告其他开发人员(包括他 future 的自己),以这种方式编写该行有一个非常具体的原因,以避免任何人试图将其替换为 (可能看起来更自然)第二,引入错误的错误版本。

关于java - "offset or count might be near -1>>>1."什么意思,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16054289/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com