Object equality in Java

The first time I paid attention to the equals() method was when preparing for SCJP exam, where you have to know what the output of some lines of code will be. That was simple enough – follow the logic of the code, and make sure that you are not accidentally overloading equals instead of overriding it.

A few years later, I revisited equals() ( and hashcode() ) when reading Joshua Bloch’s Effective Java. Chapter 3, “Methods Common to All Objects” shows how to, and why you should, properly implement equals() method. This must be required reading for every Java programmer, even if you ever only write CRUD applications in Struts, and are never going to use any of it.

Recently, I read Angelika Langer‘s article on this subject. If, like me, you have read the Effective Java book, and think that you know all that you need to about Object equality, think again!

Angelika Langer and Klaus Kreft disect various approaches to implementing equals() – Secrets of equals().

The gist of it is that although implementing equals() for a final class, or a class with a final equals() method is reasonably straightforward, there is no one correct way of doing that with mixed-type comparisons allowed between objects of different types in the same class hierarchy.
The second thing to keep in mind is that if you are overriding a class that implements equals(), and you override the equals() method you have to pay particular attention to whether the superclass’s equals() method allows mixed-type comparisons or not –

If the designer of such a non-final class decides in favor of implementing equals() using instanceof , then no subclass can ever add fields and override equals() without violating the transitivity requirement of the equals() contract.
If the designer decides in favor of implementing equals() using getClass() , then no subclass object will ever be comparable to a superclass object and trivial extensions may not make a lot of sense.

There is a follow up article showing one way of Implementing equals() To Allow Mixed-Type Comparison.