Possible Duplicate:
Weird Java Boxing
Recently while I was reading about wrapper classes I came through this strange case:
Integer i1 = 1000;
Integer i2 = 1000;
if(i1 != i2) System.out.println("different objects");
if(i1 == i2) System.out.println("same object");
Which prints:
different objects
and
Integer i1 = 10;
Integer i2 = 10;
if(i1 != i2) System.out.println("different objects");
if(i1 == i2) System.out.println("same object");
Which prints:
same object
Is there any reasonable explanation for this case?
Thanks
The reason why == returns true for the second case is because the primitive values boxed by the wrappers are sufficiently small to be interned to the same value at runtime. Therefore they're equal.
In the first case, Java's integer cache is not large enough to contain the number 1000, so you end up creating two distinct wrapper objects, comparing which by reference returns false.
The use of said cache can be found in the Integer#valueOf(int) method (where IntegerCache.high defaults to 127):
public static Integer valueOf(int i) {
if(i >= -128 && i <= IntegerCache.high)
return IntegerCache.cache[i + 128];
else
return new Integer(i);
}
As Amber says, if you use .equals() then both cases will invariably return true because it unboxes them where necessary, then compares their primitive values.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With