加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > Java > 正文

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

发布时间:2020-12-15 05:11:01 所属栏目:Java 来源:网络整理
导读:这些值如何在 java中相同? -Integer.MIN_VALUE == Integer.MIN_VALUE 价值观是: -2147483648 : -2147483648 我试着比较它并返回真实[惊人!] 解决方法 是的,这是预期的行为. int的范围是-2147483648到2147483647. 从JLS section 15.15.4(强调我的): For i
这些值如何在 java中相同?

-Integer.MIN_VALUE == Integer.MIN_VALUE

价值观是:

-2147483648 : -2147483648

我试着比较它并返回真实[惊人!]

解决方法

是的,这是预期的行为. 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_VALUE是Integer.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));
}

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读