6

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 1

11

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.

Sign up to request clarification or add additional context in comments.

5 Comments

I'm afraid to ask how did you learn about this behavior. Answering this question in under a minute is very impressive!
@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.
@dasblinkenlight for someone who works so much with core libraries; this should really be "off the shelf"..
I do indeed know the hashCode implementation of Map.Entry off the top of my head.
FWIW here's "Jon Skeet's famous Shanghai date discontinuity answer": stackoverflow.com/a/6841479/1441122

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.