EclipseZone – Generating good hashCode() and …
EclipseZone has an interesting thread going about generating good hashCode() and equals(Object) methods. The article starts off showcasing a new feature in Eclipse 3.2M5 which autogenerates the two methods based on the fields in the class. The interesting part though is in the comments and centres around the validity of using classA instanceof classB versus classA.getClass() == classB.getClass().
This is something I had never really though about, but apparently the former is just plain wrong and the latter is the correct implementation within an equals(Object) method. The reason has to do with class heirarchies and the math behind the equals method. The Javadocs for equals() states that it should be:
- Reflexive – so for any non-null reference x, x.equals(x) should return true
- Symmetric – so for any non-null references x & y, x.equals(y) should return true if and only if y.equals(x) returns true
- Transitive – so for non-null references x, y & z, if x.equals(y) returns true and y.equals(z) returns true, then x,equals(z) should return true
However, instanceof violates these rules due to inheritance. Specifically, it is non-symmetric. Whereas x.getClass() == y.getClass() maintains the mathematical relationships between references by ensuring that the classes are the same.
This is something I never knew before. I had always been taught to just use the instanceof operator to short circuit the test and ensure that both classes were the same before making any cast. I think I have a few classes to rewrite in my TeamDocs application.
I strongly suggest that any Java developers read through the entire thread. It does degrade a little in the middle, but the arguments on all sides are worth following. Overall, it is one of the best discussions on this topic that I have ever seen.