equals()
and hashCode()
are used conjunctively in certain collections, such as HashSet
and HashMap
, so you have to make sure that if you use these collections, you override hashCode
according to the contract.
If you don't override hashCode
at all, then you'll have problems with HashSet
and HashMap
. In particular, two objects that are "equal" may be put in different hash buckets even though they should be equal.
If you do override hashCode
, but do so poorly, then you'll have performance issues. All your entries for HashSet
and HashMap
will be put into the same bucket, and you'll lose the O(1) performance and have O(n) instead. This is because the data structure essentially becomes a linearly-checked linked list.
As for breaking programs outside of these conditions, it's not likely, but you never know when an API (especially in 3rd-party libraries) is going to depend on this contract. The contract is upheld for objects that don't implement either of them, so it's conceivable that a library may depend on this somewhere without using hash buckets.
In any case, implementing a good hashCode
is easy, especially if you're using an IDE. Eclipse and Netbeans both have the ability to generate equals
and hashCode
for you in a way that all contracts are followed, including the inverse rules of equals
(the assertion that a.equals(b) == b.equals(a)
). All you need to do is select the fields you want to be included and go.