Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I compare two Integers? [duplicate]

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.

like image 519
Daniel Rikowski Avatar asked Dec 09 '09 13:12

Daniel Rikowski


People also ask

How do you compare two integer values?

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.

Can you compare double integers?

All int s are exactly representable as double .

How do you compare integers and integers?

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.


1 Answers

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().

like image 116
Jeff Avatar answered Sep 21 '22 15:09

Jeff