Comparing Integer values in Java, strange behavior

Go To StackoverFlow.com

24

Walk with me ..

Integer x = 23;
Integer y = 23;

if (x == y)
    System.out.println("what else");      // All is well as expected
else
    System.out.println("...");

While

Integer x = someObject.getIndex();
Integer y = someOtherObject.getSomeOtherIndex();

if (x == y)
    System.out.println("what else");  
else
    System.out.println("...");        // Prints this 

Hmm ... I try casting to int

int x = someObject.getIndex();
int y = someOtherObject.getSomeOtherIndex()

if (x == y)       
    System.out.println("what else");   // works fine
else
    System.out.println("...");  

Are they both Integers?

System.out.println(x.getClass().getName());              // java.lang.Integer
System.out.println(y.getClass().getName());              // java.lang.Integer
System.out.println(someObject.getIndex());               // java.lang.Integer
System.out.println(someOtherObject.getSomeOtherIndex()); // java.lang.Integer

What do you guys think? What would explain something like this?

2012-04-03 21:58
by JAM
possible duplicate of How != operator and == operator works in Java?assylias 2012-04-03 22:08
What do getIndex(); and getSomeOtherIndex() do - XXX 2016-02-17 12:08


43

You're comparing Integer values, which are references. You're coming up with those references via autoboxing. For some values (guaranteed for -128 to 127) the JRE maintains a cache of Integer objects. For higher values, it doesn't. From section 5.1.7 of the JLS:

If the value p being boxed is true, false, a byte, or a char in the range \u0000 to \u007f, or an int or short number between -128 and 127 (inclusive), then let r1 and r2 be the results of any two boxing conversions of p. It is always the case that r1 == r2.

Ideally, boxing a given primitive value p, would always yield an identical reference. In practice, this may not be feasible using existing implementation techniques. The rules above are a pragmatic compromise. The final clause above requires that certain common values always be boxed into indistinguishable objects. The implementation may cache these, lazily or eagerly. For other values, this formulation disallows any assumptions about the identity of the boxed values on the programmer's part. This would allow (but not require) sharing of some or all of these references.

This ensures that in most common cases, the behavior will be the desired one, without imposing an undue performance penalty, especially on small devices. Less memory-limited implementations might, for example, cache all char and short values, as well as int and long values in the range of -32K to +32K.

Moral: don't compare Integer references when you're interested in the underlying int values. Use .equals() or get the int values first.

2012-04-03 22:00
by Jon Skeet
@JAM: Yes, either cast to int, call intValue() and compare the results, or call equals() - Jon Skeet 2012-04-03 22:04
Ok cool; Thank you Jon - JAM 2012-04-03 22:07


13

To compare the Integers correctly, you need to use .equals() or compare their primitive values by casting to int or calling intValue() on them.

Using == checks whether the two Integers are the same Object, not whether they contain the same numerical value.

    Integer a = new Integer(1);
    Integer b = new Integer(1);

    System.out.println(a.equals(b));                  //true
    System.out.println((int)a == (int)b);             //true
    System.out.println(a.intValue() == b.intValue()); //true
    System.out.println(a == b);                       //false

Edited to illustrate Jon's point from the JLS about autoboxing:

    Integer a = 1;
    Integer b = 1;
    System.out.println(a.equals(b));                  //true
    System.out.println((int)a == (int)b);             //true
    System.out.println(a.intValue() == b.intValue()); //true
    System.out.println(a == b);                       //true

versus:

    Integer a = 128;
    Integer b = 128;
    System.out.println(a.equals(b));                  //true
    System.out.println((int)a == (int)b);             //true
    System.out.println(a.intValue() == b.intValue()); //true
    System.out.println(a == b);                       //false
2012-04-03 22:02
by DNA


1

Sounds like something is funky with auto-boxing when you use == on the two integers.

I would assume that it works fine when using Integer if you use the equals() method? That would by my guess anyway.

You're not using java 1.4 or something are you?

2012-04-03 22:02
by jkerrwilson
The other answers indicate exactly why this is happening: The JVM caches small values of Integers. So, when I compare (new Integer (12) == new Integer (12)) [yields true] the JVM returns the SAME cached object for both sides of that value of 12. So, indeed the objects are the same. For large values, independently new objects are created, and this does not happen - ingyhere 2013-12-14 19:25
Ads