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?
1 Answer
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.
5 Comments
Sergey Kalinichenko
I'm afraid to ask how did you learn about this behavior. Answering this question in under a minute is very impressive!
Dawood ibn Kareem
@dasblinkenlight Possibly he'd encountered it and thought about it before (like Jon Skeet's famous Shanghai date discontinuity answer). Or possibly the first thing he did when seeing the question was to look up the
hashCode implementation in HashMap. Either way, it's still quite impressive.Eugene
@dasblinkenlight for someone who works so much with core libraries; this should really be "off the shelf"..
Louis Wasserman
I do indeed know the hashCode implementation of
Map.Entry off the top of my head.Stuart Marks
FWIW here's "Jon Skeet's famous Shanghai date discontinuity answer": stackoverflow.com/a/6841479/1441122