Saturday, August 13, 2016
Java : Don't compare Integer objects with ==
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:
Posted by thushara at 5:52 AM