gpt4 book ai didi

java - 如何否定一个值与java [Integer.Min_Value]中的值相同

转载 作者:塔克拉玛干 更新时间:2023-11-01 21:29:47 25 4
gpt4 key购买 nike

这些值在 java 中如何相同?

-Integer.MIN_VALUE == Integer.MIN_VALUE

值是:

-2147483648 : -2147483648

我尝试比较它并返回 true [太棒了!]

最佳答案

是的,这是预期的行为。 int的范围是 -2147483648 到 +2147483647。

来自JLS section 15.15.4 (强调我的):

For integer values, negation is the same as subtraction from zero. The Java programming language uses two's-complement representation for integers, and the range of two's-complement values is not symmetric, so negation of the maximum negative int or long results in that same maximum negative number. Overflow occurs in this case, but no exception is thrown. For all integer values x, -x equals (~x)+1.

~Integer.MIN_VALUEInteger.MAX_VALUE ...当您添加一个时,它会溢出到 Integer.MIN_VALUE .

这就是为什么在实现反向比较器时,您绝不能这样做:

// BAD CODE!
public int compare(T x, T y) {
return -originalComparator.compare(x, y);
}

相反,使用这个:

// This is fine, assuming the comparator obeys its contract
public int compare(T x, T y) {
return originalComparator.compare(y, x));
}

关于java - 如何否定一个值与java [Integer.Min_Value]中的值相同,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17378837/

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