java == for Integer

9

可能是重复的问题:
Java中“==”的不一致行为?
Integer包装对象仅在值为127时共享相同实例?

我发现了Integer对象的以下 == 行为,但我无法理解它。(我很清楚应该使用equals进行这种比较,但我正在为OCPJP学习...)

简而言之,== 对于1000像预期的一样正常工作,但对于10则不然。

前面的代码片段如下:

Integer i1 = 1000;
Integer i2 = 1000;
if(i1 != i2) System.out.println("different objects");
if(i1.equals(i2)) System.out.println("meaningfully equal");

它表现得像人们所期望的一样:

different objects
meaningfully equal

后者:
Integer i3 = 10;
Integer i4 = 10;
if(i3 == i4) System.out.println("same object");
if(i3.equals(i4)) System.out.println("meaningfully equal"); 

具有以下输出:

same object
meaningfully equal

有人可以解释一下为什么会发生这种情况吗?


1
顺便提一下,尝试使用-XX:+AggressiveOpts选项,第一个将会像第二个一样运行,因为它增加了整数缓存的大小。 ;) - Peter Lawrey
2个回答

12
自从Java 5以来,引入了包装类缓存机制。下面是对Integer缓存中位于内部类IntegerCache中创建的缓存的检查。例如,以下代码将创建一个缓存:
Integer myNumber = 10
或者
Integer myNumber = Integer.valueOf(10);

在范围-128到127内创建的256个整数对象都存储在一个整数数组中,这个缓存功能可以通过查看Integer中的内部类IntegerCache来得知:

因此,在使用Integer.valueOf创建对象或直接将值赋给-128到127范围内的整数时,将返回相同的对象。因此,请考虑以下示例:

Integer i = 100;
Integer p = 100;
if (i == p)  
    System.out.println("i and p are the same.");
if (i != p)
    System.out.println("i and p are different.");   
if(i.equals(p))
    System.out.println("i and p contain the same value.");

输出结果为:

i and p are the same.
i and p contain the same value.
重要的是要注意,对象i和p只有在它们是相同对象时才相等,比较不是基于值,而是基于对象相等性。如果整数i和p超出了-128或127的范围,则不使用缓存,因此会创建新的对象。在进行值比较时,始终使用“.equals”方法。还要注意,实例化一个Integer并不会创建此缓存。
请记住,“==”始终用于对象相等性,未重载用于比较未装箱(unboxed)的值。

10

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接