Saturday, August 13, 2016

Java : Don't compare Integer objects with ==

In Java, == operator, if used between objects, compares their references. However, if you compare an object and a primitive type, Java "unboxes" the object to the primitive type and compares the primitives. This auto-conversion is a very pleasant feature of the language, but unfortunately, there is no unboxing if both types being compared to are objects.

So comparing two Integer objects will not work.

Comparing the intValue() on the objects is the way to go.

Sometimes, we may forget that two integer objects are being compared. Think of using a count as the value of a hash map. This is an integer, but due to the way generics are implemented, the value needs to be an Integer object. Comparing counts will need to use the intValue of the Integer object, such as needed for sorting the map by count.

The other relational operators (>, <, >=, <=) work as one might more intuitively expect. They use the Comparable.compare(T obj) method of the Integer class and work on the integer value held in the Integer instances being compared.

It is not clear why the Java language designers chose to wire == operator very differently from the other relational operators.

So the lesson is that whenever you work with Integer instances, all relational operators except the equality operator (==) works in the intuitive sense of comparing the integers. For equality, you could use one of the following:


boolean Integer.equals(Object obj)  

int Integer.compareTo(Integer another)

integerObj1.intValue() == integerObj2.intValue()


2 comments:

Jeffy said...

I just stumbled upon your blog and wanted to say that I have really enjoyed reading your blog posts. Any way I’ll be subscribing to your feed and I hope you post again soon.

Digital Marketing Company in Chennnai

Shalini said...

Superb. I really enjoyed very much with this article here. Really it is an amazing article I had ever read. I hope it will help a lot for all. Thank you so much for this amazing posts and please keep update like this excellent article.thank you for sharing such a great blog with us. expecting for your.
Digital Marketing Company in India