整数构造变体
大家好,我遇到了一个有趣的事件,正在寻找解释。
在 Java 1.6 中:
Integer a = new Integer(5);
Integer b = new Integer(5);
System.out.println(a == b);
Integer c = 5;
Integer d = 5;
System.out.println(c == d);
我得到:
false
true
在 Eclipse 中我签入了调试器。 a
和 b
是不同的对象,而 c
和 d
是相同的对象(但与 a
和 b
)。
谁能告诉我幕后发生的事情吗?这就是 JVM 的魔力吗?意识到 Integer(5) 已经在堆栈中了吗?
Hey all, I ran into an interesting occurrence and am looking for an explanation.
In Java 1.6:
Integer a = new Integer(5);
Integer b = new Integer(5);
System.out.println(a == b);
Integer c = 5;
Integer d = 5;
System.out.println(c == d);
I get:
false
true
In Eclipse I checked in the debugger. a
and b
are different objects, while c
and d
are the same objects (but different from a
and b
).
Can anyone clue me in on what's going on under the hood? Is this JVM magic? Realizing that a Integer(5) is already on the stack?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
Java 会缓存它认为足够接近于零的值的
Integer
实例(如果它们是常量)。使用new
手动创建Integer
会绕过该缓存。您可以使用int
调用Integer.valueOf
来获取相应的Integer
,而无需绕过缓存。您可能需要在您选择的搜索引擎上搜索“JVM 整数缓存”以获取更多信息。
Java caches
Integer
instances for values it deems close enough to zero if they're constants. Manually creating anInteger
usingnew
bypasses that cache. You can callInteger.valueOf
with anint
to get the correspondingInteger
without bypassing the cache.You may want to search for "JVM Integer cache" on your search engine of choice for more information.
@icktoofay 的回答很明确,但评论却把水搅浑了。
JLS 版本 3.0要求将 -128 到 +127 范围内的整数自动装箱为缓存值;请参阅 JLS 第 5.1.7 节。换句话说,对于所有兼容的 Java 5 及更高版本的平台,您可以依赖此行为来处理该范围内的整数。
(类似的要求适用于布尔值、字节、字符和短整型。)
JLS 特别允许相同的自动装箱行为扩展到更广泛的值。
@icktoofay's answer nails it, but the comments are muddying the waters.
The JLS edition 3.0 requires that integers in the ranges -128 to +127 are autoboxed to cached values; see JLS section 5.1.7. In other words, you can rely on this behaviour for integers in that range, for all complaint Java 5 and later platforms.
(Similar requirements apply to booleans, bytes, chars and shorts.)
The JLS specifically allows the same autoboxing behaviour to extend across a wider range of values.