Re: Force implementation of equals() and hashCode()?
Chris wrote:
Is there any way to force a class that implements an interface to
implement both equals() and hashCode()?
I want all classes that implement a certain interface to work properly
in a HashMap. This means they need to implement their own version of
equals() and hashCode(). Trouble is, if I add those methods to the
interface, the system doesn't squawk if the class doesn't implement
them, because it just inherits them from Object.
I don't believe there really is such a way. Of course, if incorrect behavior
in a HashMap doesn't force them to do it right, they're pretty hopeless anyway.
The documenation for the collection classes stresses that the classes only
work properly for base types that implement 'equals()' and 'hashCode()'
consistently.
It happens that you might not need to force client code to override those
methods at all. The default implementations work just fine with collections,
for certain values of "just fine". Those values likely won't include what the
coder has in mind, but that's a general liability with collections and not
unique to your project. See, for example,
<http://java.sun.com/javase/6/docs/api/java/util/Collection.html>
<http://java.sun.com/javase/6/docs/api/java/lang/Object.html#hashCode()>
The requirement to consider overriding these two methods specifically,
particularly in the context of collections, is fundamental to any competence
in Java development. If you have to tell client programmers this, let alone
enforce it, you're in deeper doo-doo than any interface restrictions could
ever fix.
Joshua Bloch, /Effective Java/, <http://java.sun.com/docs/books/effective/>,
items 8 and 9.
I like item 53, too, but it has nothing to do with this discussion.
--
Lew