Strange Wrapper Classes behavior with == and != [duplicate]
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.
Integer i1 = 1000;
compiler understands it as an int that is why i1 == i2 // return true
but while i1
and i2
are big == test return false
Integer i1 = 10000000;
Integer i2 = 10000000;
if(i1 != i2) System.out.println("different objects"); // true
if(i1 == i2) System.out.println("same object"); // false
notice :
Integer i1 = 100;
Integer i2 = 100;
System.out.println(i1 == i2); // true
i1 = 1000000;
i2 = 1000000;
System.out.println(i1 == i2); // false
do not test equality with == for Objects. it just compares their reference. .equal()
check whether two objects are same or not.
Integer i1 = 1000000;
Integer i2 = 1000000;
i1 == i2 // false
i1.equals(i2) // true
I just tried this, and all it prints for me is
different objects
as expected, since you are creating two different wrapper objects, even though they happen to contain the same value.
As Amber implies in the above comment,
if(i1.equals(i2)) System.out.println("same value");
does indeed print
same value
精彩评论