java: Always override hashCode() when you override equals
Why override equals() and hashCode()?
@articleWhat would happen if
Integer
did not overrideequals()
andhashCode()
? Nothing, if we never used anInteger
as a key in aHashMap
or other hash-based collection. However, if we were to use such anInteger
object for a key in aHashMap
, we would not be able to reliably retrieve the associated value, unless we used the exact sameInteger
instance in theget()
call as we did in theput()
call. This would require ensuring that we only use a single instance of theInteger
object corresponding to a particular integer value throughout our program. Needless to say, this approach would be inconvenient and error prone.The interface contract for
Object
requires that if two objects are equal according toequals()
, then they must have the samehashCode()
value. Why does our root object class needhashCode()
, when its discriminating ability is entirely subsumed by that ofequals()
? ThehashCode()
method exists purely for efficiency. The Java platform architects anticipated the importance of hash-based collection classes -- such asHashtable
,HashMap
, andHashSet
-- in typical Java applications, and comparing against many objects withequals()
can be computationally expensive. Having every Java object supporthashCode()
allows for efficient storage and retrieval using hash-based collections.