Posted by caleb_phillips
on September 28, 2006 at 7:01 AM PDT
I don't know the feasibility of a feature like this, but I wanted to throw it out there. It would be great if there was a simple way to implement equals and hashCode (a la Effective Java Items 7 and 8) simply by indicating which fields are significant to determining equality. It's true that Effective Java lays out a good way to implement those methods, but it's easy for someone who doesn't quite understand all of the finer points to do something wrong. The spirit of the solution might be something like adding a standard annotation like @SignificantToEquality. The default behavior of Object.equals and Object.hashCode could be modified to look for any fields annotated as such. If there were any annotated fields it could perform a proper equals comparison as outlined in the book. If there were not any annotated fields it could just check reference equality to preserve backwards compatibility (?).
The inspiration for this idea came from the inclusion of enums in 1.5. Again Effective Java (Item 21) lays out in detail how to implement a typesafe enumeration, but there are several fine points, especially in regard to serialization and extensions, that are easy to miss. Adding enums to the language helps the average developer to do the right thing and avoid the old non-typesafe enum pattern, without having to understand all the down and dirty details. I thought similar support for implementing true type equality would help developers to use the power of polymorphism, especially with the collections framework, which is so important in ORM, while avoiding some of the pitfalls.