http://leepoint.net/notes-java/data/expressions/22compareobjects.html
It turns out that defining equals() isn’t trivial; in fact it’s moderately hard to get it right, especially in the case of subclasses. The best treatment of the issues is in Horstmann’s Core Java Vol 1.
If equals() must always be overridden, then what is a good approach for not being cornered into having to do object comparison? What are some good ‘design’ alternatives?
EDIT:
I’m not sure this is coming across the way that I had intended. Maybe the question should be more along the lines of ‘Why would you want to compare two objects?’ Based upon your answer to that question, is there an alternative solution to comparison? I don’t mean, a different implementation of equals. I mean, not using equality at all. I think the key point is to start with that question, why would you want to compare two objects.
You are mistaken. You should override equals as seldom as possible.
All this info comes from Effective Java, Second Edition (Josh Bloch). The first edition chapter on this is still available as a free download.
From Effective Java:
The problem with arbitrarily overriding equals/hashCode is inheritance. Some equals implementations advocate testing it like this:
In fact, the Eclipse (3.4) Java editor does just this when you generate the method using the source tools. According to Bloch, this is a mistake as it violates the Liskov substitution principle.
From Effective Java:
Two ways to minimize equality problems are described in the Classes and Interfaces chapter:
As far as I can see, the only alternative is to test equality in a form external to the class, and how that would be performed would depend on the design of the type and the context you were trying to use it in.
For example, you might define an interface that documents how it was to be compared. In the code below, Service instances might be replaced at runtime with a newer version of the same class – in which case, having different ClassLoaders, equals comparisons would always return false, so overriding equals/hashCode would be redundant.
The obvious example is to test if two Strings are the same (or two Files, or URIs). For example, what if you wanted to build up a set of files to parse. By definition, the set contains only unique elements. Java’s Set type relies on the equals/hashCode methods to enforce uniqueness of its elements.