【发布时间】:2012-03-08 18:57:47
【问题描述】:
可能重复:
Inconsistent behavior on java's ==
Integer wrapper objects share the same instances only within the value 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
谁能解释一下为什么会这样?
【问题讨论】:
-
BTW 尝试使用
-XX:+AggressiveOpts,第一个将表现为第二个,因为它增加了整数缓存的大小。 ;)