1

为什么,鉴于:

int a = ..., b = ... ;

这是不安全的:

a - b

但这是安全的:

a > b

安全我的意思是保证不会受到溢出的影响(我正在写一个整数Comparator)。

4

2 回答 2

2

The comparison a > b is itself safe, because neither a nor b are changed. The operation a - b can be unsafe because overflow is possible.

However, a previous overflow may affect the correctness of such a comparison a > b done later. Subtracting a really large negative number will result in overflow, in that the result can be less than the original number (in math, subtracting a negative number should increase the original number), meaning a > b may be an unexpected result.

If a - b is used in a Comparator, at first it looks like it satisfies the contract of Comparator: return a number less than zero, equal to zero, or greater than zero if the value is less than, equal to, or greater than another value. But that's only true if overflow does not occur.

If a = 1000 and b = Integer.MIN_VALUE + 100 (a very large negative number, -2147483548), then a - b will overflow. The true mathematical result would be 500 - Integer.MIN_VALUE, a value larger than Integer.MAX_VALUE (2147484548). So the positive return value would indicate that a > b, which is obviously true.

But with overflow, the value winds up being less than zero (-2147482748), erroneously indicating that a < b.

于 2013-09-05T21:20:33.383 回答
1

好吧,这取决于...请参阅System.nanoTime(),它建议t1 - t0 < 0, not t1 < t0进行时间比较...

于 2013-09-05T21:53:57.130 回答