Skip to main content

Language support for hashCode and equals

2 replies [Last post]
caleb_phillips
Offline
Joined: 2006-09-28

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.

Thanks,
Caleb

Reply viewing options

Select your preferred way to display the comments and click "Save settings" to activate your changes.
soupdragon
Offline
Joined: 2006-01-07

Might be a little slow, don't you think? Especially with very simple cases. Every call to equals or hashCode involving a scan of the fields table.

But, if you like the idea, it's easy enough to write your own version. You could write a class like:

[code]
public class AutoEquals {
...
public AutoEquals(Class clazz) {
..

public boolean equals(Object o1, Object o2) {
...
public int hashCode(Object o1) {
...
[/code]
The class could pick up the annotations on construction, so as to reduce the overheads of running, and you could create a static instance for each class.

caleb_phillips
Offline
Joined: 2006-09-28

I really have no idea about the cost of the annotation stuff. I have only used them as a consumer, I haven't created or processed any myself. I was hoping it might spark an idea for somebody with more knowledge. Thanks for your feedback and your suggestion.