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?
Yes, if you override
equals, you should always also override
hashCode, even if you don't expect your object to be stored in a
HashSet. There are several reasons.
Your objects might not be stored in a
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
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
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.
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
hashCode is sometimes used for short-circuiting an equality check.
The bottom line is that the point of the
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.