Why Java does not see that Integers are equal?

Roman picture Roman · Dec 13, 2010 · Viewed 33.2k times · Source

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

aioobe picture aioobe · Dec 13, 2010

Check out this article: Boxed values and equality

When comparing wrapper types such as Integers, Longs or Booleans using == or !=, you're comparing them as references, not as values.

If two variables point at different objects, they will not == each other, even if the objects represent the same value.

Example: Comparing different Integer objects using == and !=.

Integer i = new Integer(10);
Integer j = new Integer(10);
System.out.println(i == j); // false
System.out.println(i != j); // true

The solution is to compare the values using .equals()

Example: Compare objects using .equals(…)

Integer i = new Integer(10);
Integer j = new Integer(10);
System.out.println(i.equals(j)); // true

…or to unbox the operands explicitly.

Example: Force unboxing by casting:

Integer i = new Integer(10);
Integer j = new Integer(10);
System.out.println((int) i == (int) j); // true

References / further reading