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()
About these ads

About ChandanPandey

Try to come up with a good design as by product of good coding practices

Posted on January 4, 2013, in Java and tagged , . Bookmark the permalink. 2 Comments.

  1. 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);
    }

  2. 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.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

Follow

Get every new post delivered to your Inbox.

Join 32 other followers

%d bloggers like this: