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?

Sergey Kalinichenko
  • 714,442
  • 84
  • 1,110
  • 1,523
ViralPanda
  • 83
  • 8

1 Answers1

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.

Louis Wasserman
  • 191,574
  • 25
  • 345
  • 413
  • 3
    I'm afraid to ask how did you learn about this behavior. Answering this question in under a minute is very impressive! – Sergey Kalinichenko Jun 26 '17 at 23:57
  • 1
    @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. – Dawood ibn Kareem Jun 27 '17 at 00:12
  • @dasblinkenlight for *someone* who works so much with core libraries; this should really be "off the shelf".. – Eugene Jun 27 '17 at 18:31
  • 5
    I do indeed know the hashCode implementation of `Map.Entry` off the top of my head. – Louis Wasserman Jun 27 '17 at 18:48
  • FWIW here's "Jon Skeet's famous Shanghai date discontinuity answer": https://stackoverflow.com/a/6841479/1441122 – Stuart Marks Jun 27 '17 at 22:58