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.
compare(int x, int y) compare() compares two int values numerically and returns an integer value. If x>y then the method returns an int value greater than zero. If x=y then the method returns zero.
All int s are exactly representable as double .
In Java, int is a primitive data type while Integer is a Wrapper class. int, being a primitive data type has got less flexibility. We can only store the binary value of an integer in it. Since Integer is a wrapper class for int data type, it gives us more flexibility in storing, converting and manipulating an int data.
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()
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With