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