This question already has an answer here:
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.
I would go with x.equals(y) because that's consistent way to check equality for all classes.
As far as performance goes, equals is actually more expensive because it ends up calling intValue().
EDIT: You should avoid autoboxing in most cases. It can get really confusing, especially the author doesn't know what he was doing. You can try this code and you will be surprised by the result;
"equals" is it. To be on the safe side, you should test for null-ness:
the x==y tests for null==null, which IMHO should be true.
The code will be inlined by the JIT if it is called often enough, so performance considerations should not matter.
Of course, avoiding "Integer" in favor of plain "int" is the best way, if you can.
[Added]
Also, the null-check is needed to guarantee that the equality test is symmetric -- x.equals(y) should by the same as y.equals(x), but isn't if one of them is null.
The Integer class implements
Comparable<Integer>
, so you could try,also, if rather than equality, you are looking to compare these integers, then,
x.compareTo(y) < 0
will tell you if x is less than y.x.compareTo(y) > 0
will tell you if x is greater than y.Of course, it would be wise, in these examples, to ensure that x is non-null before making these calls.
This is what the equals method does:
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 theequals()
call anyway, though I don't know that for certain.I generally would use the primitive
int
, but if I had to useInteger
, I would stick withequals()
.Use the
equals
method. Why are you so worried that it's expensive?I just encountered this in my code and it took me a while to figure it out. I was doing an intersection of two sorted lists and was only getting small numbers in my output. I could get it to work by using
(x - y == 0)
instead of(x == y)
during comparison.