Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

EDIT: OK, OK, I misread. I'm not comparing an int to an Integer. Duly noted.

My SCJP book says:

When == is used to compare a primitive to a wrapper, the wrapper will be unwrapped and the comparison will be primitive to primitive.

So you'd think this code would print true:

    Integer i1 = 1; //if this were int it'd be correct and behave as the book says.
    Integer i2 = new Integer(1);
    System.out.println(i1 == i2);

but it prints false.

Also, according to my book, this should print true:

Integer i1 = 1000; //it does print `true` with i1 = 1000, but not i1 = 1, and one of the answers explained why.
Integer i2 = 1000;
System.out.println(i1 != i2);

Nope. It's false.

What gives?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
93 views
Welcome To Ask or Share your Answers For Others

1 Answer

Note also that newer versions of Java cache Integers in the -128 to 127 range (256 values), meaning that:

Integer i1, i2;

i1 = 127;
i2 = 127;
System.out.println(i1 == i2);

i1 = 128;
i2 = 128;
System.out.println(i1 == i2);

Will print true and false. (see it on ideone)

Moral: To avoid problems, always use .equals() when comparing two objects.

You can rely on unboxing when you are using == to compare a wrapped primitive to a primitive (eg: Integer with int), but if you are comparing two Integers with == that will fail for the reasons @dan04 explained.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...