HashMap裏的hash、indexFor方法

hash和indexFor方法屬於HashMap類,爲什麼jdk開發者需要使用另一種hash方法而不用鍵對象自己的hashcode方法,下面看一下hash和indexFor的源代碼:

/** 
 * Applies a supplemental hash function to a given hashCode, which 
 * defends against poor quality hash functions.  This is critical 
 * because HashMap uses power-of-two length hash tables, that 
 * otherwise encounter collisions for hashCodes that do not differ 
 * in lower bits. Note: Null keys always map to hash 0, thus index 0. 
 */  
static int hash(int h) {  
    // This function ensures that hashCodes that differ only by  
    // constant multiples at each bit position have a bounded  
    // number of collisions (approximately 8 at default load factor).  
    h ^= (h >>> 20) ^ (h >>> 12);  
    return h ^ (h >>> 7) ^ (h >>> 4);  
}  
   
/** 
 * Returns index for hash code h. 
 */  
static int indexFor(int h, int length) {  
    return h & (length-1);  
}  

在hashcode值上再應用hash方法主要爲了解決在低位上的衝突,藉助一個例子來理解:

假設鍵對象的hashcode方法只返回三個值,31、63、95,它們都是int所以都是32位

31 = 0000 0000 0000 0000 0000 0000 0001 1111

63 = 0000 0000 0000 0000 0000 0000 0011 1111

95 = 0000 0000 0000 0000 0000 0000 0101 1111

hashMap的長度是16(2^4)

如果不使用hash方法:

indexFor將會返回

31 = 0000 0000 0000 0000 0000 0000 0001 1111 --> 1111 = 15

63 = 0000 0000 0000 0000 0000 0000 0011 1111 --> 1111 = 15

95 = 0000 0000 0000 0000 0000 0000 0101 1111 --> 1111 = 15

因爲當調用indexFor方法,將會進行31&15、63&15、95&15的與操作

由於上面三個數最後四位都是1,indexFor後的值相同,雖然有不同的hashcode但是都會存在索引值爲15的位置上

如果使用hash方法:

31 = 0000 0000 0000 0000 0000 0000 0001 1111 --> 0000 0000 0000 0000 0000 0000 0001 1110

63 = 0000 0000 0000 0000 0000 0000 0011 1111 --> 0000 0000 0000 0000 0000 0000 0011 1100

95 = 0000 0000 0000 0000 0000 0000 0101 1111 --> 0000 0000 0000 0000 0000 0000 0101 1010

使用新的hash值再調indexFor方法

0000 0000 0000 0000 0000 0000 0001 1110 --> 1110 = 14

0000 0000 0000 0000 0000 0000 0011 1100 --> 1100 = 12

0000 0000 0000 0000 0000 0000 0101 1010 --> 1010 = 10

使用了hash方法後被映射到了新的位置上

如果兩個鍵對象有相同的hashcode,將會映射到相同的位置上。

如果兩個鍵對象hashcode不同,也有可能映射到相同的位置上。



發佈了54 篇原創文章 · 獲贊 4 · 訪問量 2萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章