How do I compare two Integers?

Daniel Rikowski picture Daniel Rikowski · Dec 9, 2009 · Viewed 170.2k times · Source

I have to compare two Integer objects (not int). What is the canonical way to compare them?

Integer x = ...
Integer y = ...

I can think of this:

if (x == y) 

The == operator only compares references, so this will only work for lower integer values. But perhaps auto-boxing kicks in...?

if (x.equals(y)) 

This looks like an expensive operation. Are there any hash codes calculated this way?

if (x.intValue() == y.intValue())

A little bit verbose...

EDIT: Thank you for your responses. Although I know what to do now, the facts are distributed on all of the existing answers (even the deleted ones :)) and I don't really know, which one to accept. So I'll accept the best answer, which refers to all three comparison possibilities, or at least the first two.

Answer

Jeff picture Jeff · Dec 9, 2009

This is what the equals method does:

public boolean equals(Object obj) {
    if (obj instanceof Integer) {
        return value == ((Integer)obj).intValue();
    }
    return false;
}

As you can see, there's no hash code calculation, but there are a few other operations taking place there. Although x.intValue() == y.intValue() might be slightly faster, you're getting into micro-optimization territory there. Plus the compiler might optimize the equals() call anyway, though I don't know that for certain.

I generally would use the primitive int, but if I had to use Integer, I would stick with equals().