Use .intValue() or .equals()?

By abhirama

During a code review my mentor suggested I replace the below line

foo.intValue() == moo.intValue()

with

foo.equals(moo)

I differed saying that the .intValue() is more readable than .equals(). If you read the line with the comparision done using .intValue() method it is very obvious that you are trying to equate two integers. But if the same is done using .equals() you have to see the type of the object being compared to realize that you are trying to equate two integers. Also if you open up Integer class and see .equals() method, it internally uses .intValue() for comparison. His line of reasoning was that if you use .equals() you are handing over the equality operation to JVM. So in the next version of JDK if some optimization is done for comparison, you stand to gain from it. At that instance I did not completely agree with it.

Later I came across this blog post. When I completed reading it I could not agree more with my mentor’s line of reasoning.

Leave a Reply