本文介绍了是否保证新的Integer(i)== i在Java?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

请考虑以下代码段:

  int i = 99999999; 
byte b = 99;
short s = 9999;
整数ii = Integer.valueOf(9); //应该在缓存内

System.out.println(new Integer(i)== i); //true
System.out.println(new Integer(b)== b); //true
System.out.println(new Integer(s)== s); //true
System.out.println(new Integer(ii)== ii); //false

很明显为什么最后一行会始终 false:我们使用 == 引用标识比较和 / code>对象将永远不为已经存在的对象 ==



问题是前三行: 比较 int 整数自动取消装箱?有没有情况下,原语将被自动装箱,而不是参考身份比较执行? (这将全部 false !)

解决方案

指定二进制数字促销的规则。部分:

二进制数字促销适用于多个数字运算符,包括数值相等运算符==和!=。



(数字等式运算符==和!=)指定:

相反,(参考均等运算符==和!=) p>

这符合对装箱和取消装箱的共同理解,只有当不匹配时才会这样做。 p>

Consider the following snippet:

    int i = 99999999;
    byte b = 99;
    short s = 9999;
    Integer ii = Integer.valueOf(9); // should be within cache

    System.out.println(new Integer(i) == i); // "true"
    System.out.println(new Integer(b) == b); // "true"
    System.out.println(new Integer(s) == s); // "true"
    System.out.println(new Integer(ii) == ii); // "false"

It's obvious why the last line will ALWAYS prints "false": we're using == reference identity comparison, and a new object will NEVER be == to an already existing object.

The question is about the first 3 lines: are those comparisons guaranteed to be on the primitive int, with the Integer auto-unboxed? Are there cases where the primitive would be auto-boxed instead, and reference identity comparisons are performed? (which would all then be false!)

解决方案

Yes. JLS §5.6.2 specifies the rules for binary numeric promotion. In part:

Binary numeric promotion applies for several numeric operators, including "the numerical equality operators == and !=."

JLS §15.21.1 (Numerical Equality Operators == and !=) specifies:

In contrast, JLS §15.21.3 (Reference Equality Operators == and !=) provides:

This fits the common understanding of boxing and unboxing, that's it only done when there's a mismatch.

这篇关于是否保证新的Integer(i)== i在Java?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-31 00:20