Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is HashCode zero for HashMap containing values that are same as keys

Tags:

java

hashmap

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?

like image 478
ViralPanda Avatar asked Jun 26 '17 23:06

ViralPanda


People also ask

What is the hash function in a hashmap?

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.

How to find two keys with same hash in a hashmap?

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

Why override equals and hashCode methods of a hashmap?

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.

Can a hash function return different hash codes for different keys?

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.


1 Answers

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.

like image 81
Louis Wasserman Avatar answered Nov 14 '22 23:11

Louis Wasserman