Comparing Integer in Java -autoboxing does not apply there
Hmm.. it came as most basic surprise for me, I wrote
this.questionId==question.getQuestionId()
where questionid is of type Integer (Object and not primitive).
Logically, it’s a reference comparison and should fail, but since its a wrapper for primitive type and a “special” scenario, my expectation was autoboxing will also apply here and will work properly, but no – it did not.
Correct way is either to use equals or just use intvalue
this.questionId.intValue()==question.getQuestionId().intValue()
Posted on January 4, 2013, in Java and tagged autoboxing, Integer comparision. Bookmark the permalink. 2 Comments.
Autoboxing calls Integer.valueOf(int i) which uses a cache for Integer Object going from -127 to 127, for other values a new Integer is created each time. So equality will hold for some values only (may be confusing if you test only with some values, so as you said use .equals is the sure way to go).
Here is the code for Integer.valueOf(int i)
public static Integer valueOf(int i) {
final int offset = 128;
if (i >= -128 && i <= 127) { // must cache
return IntegerCache.cache[i + offset];
}
return new Integer(i);
}
Let’s think about 1,4 java. If I remember correctly int == Integer was invalid syntax back in 1.4. While Integer == Integer was only reference checking. And sun wnated to have backwards compability. I Integer == Integer suddently would start to mean equals, that would break abckwards compability, so no autboxin when only Objet involved.