Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Are Java Integers always == when they're .equals()? [duplicate]

Tags:

java

wrapper

Normally, references to objects in the Java library can't be compared using ==, but I just checked:

Integer x = 5;
Integer y = x + 1;
Integer z = y - 1;
x.equals(z)
true   (boolean)
x == z
true   (boolean)

Is that just an artifact of my IDE, or are Java Integer objects guaranteed to point to the same Integer when they have the same value? The latter guarantee would simplify some code I'm writing.

like image 554
William H. Hooper Avatar asked Nov 29 '25 05:11

William H. Hooper


2 Answers

Are Java Integers always == when they're .equals()?

No. In the normal case, you cannot rely on == with Integer instances when attempting a numeric value comparison. For that you must either unbox them to int before comparing, or use equals.

What you're seeing in your example is the fact that the JDK caches and reuses a limited number of Integer instances (for Integers representing -128 to 127). From Integer.valueOf(int):

This method will always cache values in the range -128 to 127, inclusive, and may cache other values outside of this range.

Now, your code is using boxing conversions rather than Integer.valueOf, and the specification doesn't say that boxing conversions use Integer.valueOf, and yet it's likely that that's exactly what they do (in effect; e.g., that both the boxing conversion and Integer.valueOf use the same underlying mechanism and cache).

You can see that == is not reliable for Integer instances if you use a different value: (live copy)

Integer x = 524;    // <==== Changed
Integer y = x + 1;
Integer z = y - 1;
System.out.println("equals? " + x.equals(z));
System.out.println("==? " + (x == z));

Output (probably, and it's what I get on IDEOne, but again the docs say Integer may cache other values):

equals? true
==? false
like image 108
T.J. Crowder Avatar answered Dec 01 '25 21:12

T.J. Crowder


No, it is not guaranteed. For certain values (especially smaller, more commonly used ones) the value will get internalized and the same object reference will be reused. If you try the same test with 3,279,831 it will probably return false.

like image 40
Matt Avatar answered Dec 01 '25 20:12

Matt