2016-11-16 149 views
0

我正在通過哈希映射的實現,並在代碼中找到了計算哈希碼的代碼。你能解釋一下h的價值是如何在下面計算的,以及它爲什麼以這種特定的方式完成的?哈希映射中的哈希碼約束

final int hash(Object k) { 
    int h = hashSeed; 
    if (0 != h && k instanceof String) { 
     return sun.misc.Hashing.stringHash32((String) k); 
    } 

    h ^= k.hashCode(); 

    // 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); 
} 

回答

1

Hashcode使用hashCode()函數進行計算。你必須先看看這個功能。

計算下面

h ^= (h >>> 20)^(h >>> 12); 
return h^(h >>> 7)^(h >>> 4); 

其再次重新散列使用的哈希碼後的原因是爲了避免進一步的衝突。

發現,原來作爲

/** 
* 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); 
} 

見註釋。

1

這是一個辦法,以確保每個對象的散列碼是唯一的,建立一個種子做一些操作,以找到一個獨特的密鑰,該密鑰將被存儲在地圖上。

正如你所知道的一個Map商店信息是雙鍵值。然後,該方法的最重要的行是

h ^= k.hashCode(); 

你需要確保在你的代碼,如果決定要重寫的hashCode()方法,即返回由對象一個唯一的代碼/ ID,或者你可以重寫不同的對象在同一張地圖上。

我希望這個澄清一點你的疑惑