Explanation of HashMap#hash(int) method

后端 未结 2 1365
余生分开走
余生分开走 2020-12-01 07:58

Can someone please explain to me the static HashMap#hash(int) method?

What\'s the justification behind it to generate uniformly distributed hashes?

/         


        
2条回答
  •  独厮守ぢ
    2020-12-01 08:20

    I don't know how all the shifting works, but the motivation is laid out in the comments:

    The way the HashMap is implemented relies on the hashCode function being sufficiently well implemented. In particular, the lower bits of the hash value should be distributed evenly. If you have many collisions on the lower bits, the HashMap will not perform well.

    Because the implementation of hashCode is outside of the control of HashMap (every object can implement their own), they supply an additional hash function that shifts the object's hashCode around a little to ensure that the lower bits are distributed more randomly. Again, I have no idea how this works exactly (or how effective it is), but I assume it depends on at least the higher bits being distributed equally (it seems to mesh the higher bits into the lower bits).

    So what this does is to try to minimize collisions (and thus improve performance) in the presence of poorly implemented hashCode methods.

提交回复
热议问题