I noticed that in Java, hashCode
for HashMap
that only contain entries where key and values are same, eg {1:1}
, {"abc":"abc"}
etc. is always zero. Is there any reasoning behind this odd behavior?
The hash function returns a hash code which determines the bucket location in the HashMap where the Value pertaining to that Key is stored or is retrieved from. For a particular Key, a hash function always returns the same hash code. However, it is also possible that for different unique Keys the hash function may return the same hash code.
During HashMap#get (key) call, first a bucket is selected by mapping the key's hashCode to the bucket index, then the target entry is searched by calling equals () method on the key. If two keys have same hash per hashCode () method then they should not be same per equal () method
If you are implementing a custom key for hashMap, it becomes extremely important to override the equals and hashcode method of the key, in order to avoid hashMap behaving weirdly. When you ‘put’ in a hashmap, first the map finds a place in an array (bucket) based on the hashcode of the key.
For a particular Key, a hash function always returns the same hash code. However, it is also possible that for different unique Keys the hash function may return the same hash code.
This is a consequence of the specification of the hashCode()
for Map.Entry
, which requires the hash codes of the keys and values to be xor'd.
The only people who could tell you why that hash code was chosen are the people who wrote it originally, though my impression is that Java regrets specifying this (bad) hash function.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With