问题
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