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?
Best Answer
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 ofInteger
objects. For higher values, it doesn't. From section 5.1.7 of the JLS:Moral: don't compare
Integer
references when you're interested in the underlyingint
values. Use.equals()
or get theint
values first.