我发现Java中很奇怪的东西似乎是一个错误。 for循环无法正确评估32767的短值(最大值,请参见here)的条件。请参见下面的示例代码。我在这里想念什么吗?

for (short i = 32766; i <= 32767; i++) {
    System.out.println("i is now " + i);
    if (i < 0) {
        System.out.println("This should never be printed");
        break;
    }
}


预期产量:

i is now 32766
i is now 32767


实际输出:

i is now 32766
i is now 32767
i is now -32768
This should never be printed

最佳答案

每个可能的short值都是<= 32767,因为32767是the biggest number that a short can hold

这意味着if的条件将始终为true,并且循环将永远不会结束。

由于溢出(在Java中不会引发异常),该值回绕到Short.MIN_VALUE

一般说明:在Java中使用short的合法理由很少,几乎所有的计算,循环计数等操作都应使用int(或适当的long)完成。 short通常不会更快,并且通常不会节省任何空间(除非您有数组)。

10-04 11:32
查看更多