整数i = 3 vs Integer i = new Integer(3) [英] Integer i=3 vs Integer i= new Integer (3)

查看:123
本文介绍了整数i = 3 vs Integer i = new Integer(3)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在比较2段代码。第一个

I am comparing 2 pieces of code. First

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 正在打印?引用不应该不同吗?

I have doubt that in the first snippet why i==j is being printed? Shouldn't the references be different?

推荐答案

这与拳击工作方式有关。来自 JLS第5.1.7节

It's to do with how boxing works. From the JLS section 5.1.7:


如果装箱的值p为真,假,一个字节或范围为\\\到\ u007f的字符,或者在-128和127(含)之间的int或short数,然后让r1和r2为p的任意两次装箱转换的结果。总是这样的情况是r1 == r2。

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)肯定与以前创建的任何引用不同...它总是创建一个新的对象。

Basically, a Java implementation must cache the boxed representations for suitably small values, and may cache more. The == operator is just comparing references, so it's specifically detecting whether the two variables refer to the same object. In the second code snippet they definitely won't, as new Integer(3) definitely isn't the same reference as any previously created one... it always creates a new object.

由于上述规则,此代码必须始终给出相同的结果:

Due to the rules above, this code must always give the same result:

Integer x = 127;
Integer y = 127;
System.out.println(x == y); // Guarantee to print true

然而这可能是两种方式:

Whereas this could go either way:

Integer x = 128;
Integer y = 128;
System.out.println(x == y); // Might print true, might print false

这篇关于整数i = 3 vs Integer i = new Integer(3)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆