June 23, 2009 2 Comments
“How to Write an Equality Method in Java” from Artima:
equalsmethod, 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
equalsmethods 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.