Strange Wrapper Classes behavior with == and != [duplicate]

醉酒当歌 提交于 2019-12-10 19:06:23

问题


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


回答1:


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.




回答2:


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



回答3:


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


来源:https://stackoverflow.com/questions/4638023/strange-wrapper-classes-behavior-with-and

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