HashMap 中hash table 定位算法:
int hash = hash(key.hashCode()); int i = indexFor(hash, table.length);
其中indexFor和hash源碼如下:
/** * 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); } 現(xiàn)在分析一下hash算法:
h ^= (h >>> 20) ^ (h >>> 12); return h ^ (h >>> 7) ^ (h >>> 4);假設(shè)key.hashCode()的值為:0x7FFFFFFF,table.length為默認(rèn)值16。上面算法執(zhí)行如下:
得到i=15其中h^(h>>>7)^(h>>>4) 結(jié)果中的位運(yùn)行標(biāo)識(shí)是把h>>>7 換成 h>>>8來看。即最后h^(h>>>8)^(h>>>4) 運(yùn)算后hashCode值每位數(shù)值如下:8=87=7^86=6^7^85=5^8^7^64=4^7^6^5^83=3^8^6^5^8^4^72=2^7^5^4^7^3^8^61=1^6^4^3^8^6^2^7^5結(jié)果中的1、2、3三位出現(xiàn)重復(fù)位^運(yùn)算3=3^8^6^5^8^4^7 -> 3^6^5^4^72=2^7^5^4^7^3^8^6 -> 2^5^4^3^8^61=1^6^4^3^8^6^2^7^5 -> 1^4^3^8^2^7^5算法中是采用(h>>>7)而不是(h>>>8)的算法,應(yīng)該是考慮1、2、3三位出現(xiàn)重復(fù)位^運(yùn)算的情況。使得最低位上原h(huán)ashCode的8位都參與了^運(yùn)算,所以在table.length為默認(rèn)值16的情況下面,hashCode任意位的變化基本都能反應(yīng)到最終hash table 定位算法中,這種情況下只有原h(huán)ashCode第3位高1位變化不會(huì)反應(yīng)到結(jié)果中,即:0x7FFFF7FF的i=15。新聞熱點(diǎn)
疑難解答
圖片精選
網(wǎng)友關(guān)注