Java HashMap detect collision

前端 未结 3 1694
你的背包
你的背包 2021-02-06 01:00

Is there a way to detect collision in Java Hash-map ? Can any one point out some situation\'s where lot of collision\'s can take place. Of-course if you override the hashcode fo

3条回答
  •  长发绾君心
    2021-02-06 01:48

    Simple example: hashing a Long. Obviously there are 64 bits of input and only 32 bits of output. The hash of Long is documented to be:

    (int)(this.longValue()^(this.longValue()>>>32))
    

    i.e. imagine it's two int values stuck next to each other, and XOR them.

    So all of these will have a hashcode of 0:

    0
    1L | (1L << 32)
    2L | (2L << 32)
    3L | (3L << 32)
    

    etc

    I don't know whether that counts as a "huge number of collisions" but it's one example where collisions are easy to manufacture.

    Obviously any hash where there are more than 232 possible values will have collisions, but in many cases they're harder to produce. For example, while I've certainly seen hash collisions on String using just ASCII values, they're slightly harder to produce than the above.

提交回复
热议问题