ViralPanda
ViralPanda

Reputation: 83

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

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?

Upvotes: 6

Views: 215

Answers (1)

Louis Wasserman
Louis Wasserman

Reputation: 198014

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.

Upvotes: 11

Related Questions