Roman Roman - 1 month ago 6
Java Question

Why Java does not see that Integers are equal?

I have integers that are supposed to be equal (and I verify it by output). But in my

if
condition Java does not see these variables to have the same value.

I have the following code:

if (pay[0]==point[0] && pay[1]==point[1]) {
game.log.fine(">>>>>> the same");
} else {
game.log.fine(">>>>>> different");
}
game.log.fine("Compare:" + pay[0] + "," + pay[1] + " -> " + point[0] + "," + point[1]);


And it produce the following output:

FINE: >>>>>> different
FINE: Compare:: 60,145 -> 60,145


Probably I have to add that
point
is defined like that:

Integer[] point = new Integer[2];


and
pay
us taken from the loop-constructor:

for (Integer[] pay : payoffs2exchanges.keySet())


So, these two variables both have the integer type.

Answer

Objects (such as Integers) should not be compared through ==, but through .equals().

What's important to understand is that several different Integer objects can represent the same int value. When your program prints >>> different it simply says that the first object is not the same object as the second object. (While you probably want to compare the objects based on which value they represent.)

From the official guide on autoboxing:

[...] The == operator performs reference identity comparisons on Integer expressions and value equality comparisons on int expressions. [...]

It may be worth noting that autoboxing is guaranteed to return the same object for integral values in the range [-128, 127], but an implementation may, at its discretion, cache values outside of that range.

My general recommendation is to use int instead of Integer for all local / member variables. In this particular case you seem to store coordinates in a 2-element array. I would suggest that you encapsulate this in a Coordinates class or similar and override the equals method (and hashCode) in here.

See also

Comments