Sunday, December 20, 2009

classes that override equals should override hashCode

I was talking to a developer the other day who admitted to me that he had only recently found out that in Java, if you override the Object equals method, you should override the hashCode method also. He had been introduced to this practice by a checkstyle rule.

This surprised me for a couple of reasons. This developer is not a newcomer to Java, and it's the kind of thing I'd expect an experienced developer to know. I know about it myself from my first forays into Java. It's documented in the API for Object:
Note that it is generally necessary to override the hashCode method whenever this method [equals] is overridden, so as to maintain the general contract for the hashCode method, which states that equal objects must have equal hash codes.

But I suppose it's the kind of thing you might miss learning if you come into Java from another object-oriented language, and don't do a thorough job of learning the peculiarities of Java.

The other thing that surprised me was the fact that he admitted it at all. Developers rarely confess to ignorance. I guess that admitting a weakness is just too dangerous in this highly competitive field. I tend to be pretty open about my own gaps in knowledge, but I suspect it doesn't help me any, and in some cases it may hurt. Have you ever said "gee I didn't know X" and gotten a snooty look down the nose from someone? Not the kind of experience you want to repeat!

No comments:

Post a Comment