This is an efficient way to check if two values can possibly be equal.
The contract for hashcode
mandates:
JavaDocs of Object.hashCode
If two objects are equal according to the equals(Object) method, then calling the hashCode method on each of the two objects must produce the same integer result.
Therefore, if the hashes are distinct, there is not point in performing further checks.
As HashMap
requires the hashcodes for the keys anyway for choosing the buckets to put the entries in, the tradeoff is storing an additional int
per entry vs. possibly having to compute it repeatedly and having to execute equals
for the keys more often. HashMap
is more optimized for fast retrieval and insertion, less so for memory efficiency.
Side Note: HashMap
relies on keys not being mutated in any way that would change their "identity" in terms of equals
and hashcode
- while this may seem obvious, it is not explicitly mentioned in the JavaDocs for HashMap
and has led to questions in the past: Are mutable hashmap keys a dangerous practice? - this is covered by the more general Map
contract:
Note: great care must be exercised if mutable objects are used as map keys. The behavior of a map is not specified if the value of an object is changed in a manner that affects equals comparisons while the object is a key in the map.