我正在比较 2 段代码。首先
Integer i=3;
Integer j=3;
if(i==j)
System.out.println("i==j"); //prints i==j
其次,
Integer i=3;
Integer j=new Integer(3);
if(i==j)
System.out.println("i==j"); // does not print
我怀疑在第一个片段中为什么要打印 i==j
?引用不应该不同吗?
这与拳击的运作方式有关。来自JLS section 5.1.7 :
If the value p being boxed is true, false, a byte, or a char in the range \u0000 to \u007f, or an int or short number between -128 and 127 (inclusive), then let r1 and r2 be the results of any two boxing conversions of p. It is always the case that r1 == r2.
基本上,Java 实现必须缓存适当小值的装箱表示,并且可以缓存更多。 ==
运算符只是比较引用,所以它专门检测两个变量是否引用同一个对象。在第二个代码片段中,它们肯定不会,因为 new Integer(3)
绝对不是与之前创建的任何引用相同的引用...它总是创建一个新对象。
由于上述规则,此代码必须始终给出相同的结果:
Integer x = 127;
Integer y = 127;
System.out.println(x == y); // Guarantee to print true
然而这可能是两种方式:
Integer x = 128;
Integer y = 128;
System.out.println(x == y); // Might print true, might print false