HashMap如何应对hash collision ?

HashMap如何应对hash collision?  只通过key的hashCode()来区分key是不够的,因为两个不同key的hash code很容易就重合了。

当hash-code重合时,区分的办法就是 ==和equals()方法了;如果两个key的hashCode()相同而但equals()和==都不同,则将这两个key散列到同一个桶上,但不互相覆盖。

为求明白,可以总结一下equals(), ==, hashCode()呈现不同结果时,HashMap的不同行为:

两个key的hashCode()相等? 两个key是同一个对象? 两个key的equals() == true? 是否导致覆盖 备注
true true true
true true false N/A
true false true
true false false
false true true 单个key对象存入HashMap后,hashCode发生修改,然后再存一次
false true false N/A
false false true
false false false

Leave a Comment

Your email address will not be published.

This site uses Akismet to reduce spam. Learn how your comment data is processed.