I analyse the HashMap
source code in Java and get a question about the put
method.
Below is the put
method in JDK1.6:
It's just avoiding a method call when it can: If the hash (which isn't hashCode()
, it's the map's own hashing) is different from the entry's hash, it knows it doesn't have to call equals
at all. Just optimizing a bit.
value of 'hash' variable can be different to the keys hashcode. 'hash' variable is the result of calling 'hash(key.hashCode())' method. Therefore it's required to compare the hash values and also equality of keys.
It's just an optimization: comparing two integers is faster than calling equals()
.
If the two hashcodes differ, then, based on the contract of equals
and hashCode
, the map knows that the existing key isn't equal to the given key, and can go faster to the next one.