Aaron Barnard Aaron Barnard - 1 year ago 56
Java Question

Is there any practical point overriding hashcode if the class is not used as a key in a hashmap?

I have recently been learning about the hashCode function and HashMaps, and have experimented with creating my own hashCode function for my own classes. From the research I have done, the only reason, from a practical point of view, that hashCode needs to be overridden seems to be if the class is going to be used as a key in a HashMap, or if the hashCode function is used elsewhere. I understand it's part of the equals and hashCode contracts to override, and in the future another user may want to use it in a HashMap, but I want to know for understanding's sake, if the class were never used as a key, would I still need to override the hashCode function?

Answer Source

Yes, if you override equals, you should always also override hashCode, even if you don't expect your object to be stored in a HashMap or HashSet. There are several reasons.

  1. Your objects might not be stored in a HashMap or HashSet today, but six months from now, you might decide to do so, and things will seem to work ok until they break horribly. At that point, you'll say to yourself "%$^^&%*& I should have implemented hashCode!"

  2. Your objects might be used by somebody else, and they expect you to implement hashCode. When they store your objects in a HashMap and it doesn't work, they'll say "that %$^^&%*& Aaron should have implemented hashCode!"

  3. You might hand your object off to some library, and unbeknownst to you, that library might want to store your object in a hash-based collection.

  4. If your object is ever stored inside a container object, even if that container isn't itself hash-based, the container's hashCode is often logically dependent upon your object's hashCode. For example, see Arrays.hashCode or Optional.hashCode.

  5. The hashCode is sometimes used for short-circuiting an equality check.

The bottom line is that the point of the hashCode/equals contract is that everybody relies on the contract to be implemented properly. Assumptions about adherence to the contract are laced throughout large systems, not just in hash-based collections.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download