Integer construction variations

只愿长相守 提交于 2019-12-24 01:43:26

问题


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?


回答1:


Java caches Integer instances for values it deems close enough to zero if they're constants. Manually creating an Integer using new bypasses that cache. You can call Integer.valueOf with an int to get the corresponding Integer without bypassing the cache.

You may want to search for "JVM Integer cache" on your search engine of choice for more information.




回答2:


@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.



来源:https://stackoverflow.com/questions/5865056/integer-construction-variations

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!