François Schiettecatte’s Blog

To equals() or not to equals()

Posted in Java, Software Development by François Schiettecatte on June 23, 2009

“How to Write an Equality Method in Java” from Artima:

Class java.lang.Object defines an equals method, which subclasses may override. Unfortunately, it turns out that writing a correct equality method is surprisingly difficult in object-oriented languages. In fact, after studying a large body of Java code, the authors of a 2007 paper concluded that almost all implementations of equals methods are faulty.

The article goes into some depth on how to write a good equals method, and on the pitfalls that surround such a method. The article also makes a reference to “Effective Java Second Edition” by Josh Bloch which I am currently reading:

In Item 8 of Effective Java1, Josh Bloch describes the difficulty of preserving the equals contract when subclassing as a “fundamental problem of equivalence relations in object-oriented languages.” Bloch writes:

There is no way to extend an instantiable class and add a value component while preserving the equals contract, unless you are willing to forgo the benefits of object-oriented abstraction.

2 Responses

Subscribe to comments with RSS.

  1. François Schiettecatte said, on June 25, 2009 at 6:45 am

    Thanks, looks very useful.


Leave a Reply

You must be logged in to post a comment.