java: Always override hashCode() when you override equals
Why override equals() and hashCode()?
@articleWhat would happen if
Integerdid not overrideequals()andhashCode()? Nothing, if we never used anIntegeras a key in aHashMapor other hash-based collection. However, if we were to use such anIntegerobject for a key in aHashMap, we would not be able to reliably retrieve the associated value, unless we used the exact sameIntegerinstance in theget()call as we did in theput()call. This would require ensuring that we only use a single instance of theIntegerobject corresponding to a particular integer value throughout our program. Needless to say, this approach would be inconvenient and error prone.The interface contract for
Objectrequires 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.

0 Comments:
Post a Comment
<< Home