国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 學(xué)院 > 開發(fā)設(shè)計(jì) > 正文

hashmap的hash算法( 轉(zhuǎn))

2019-11-15 00:32:44
字體:
供稿:網(wǎng)友
hashmap的hash算法( 轉(zhuǎn))

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。
發(fā)表評論 共有條評論
用戶名: 密碼:
驗(yàn)證碼: 匿名發(fā)表
主站蜘蛛池模板: 衡山县| 遂宁市| 金溪县| 视频| 科尔| 雅安市| 石泉县| 辽阳县| 芜湖县| 涪陵区| 桑植县| 什邡市| 仪陇县| 无锡市| 陆良县| 永泰县| 台南县| 兴海县| 桦川县| 陵川县| 华亭县| 运城市| 珲春市| 兴海县| 正蓝旗| 吴江市| 鄂尔多斯市| 南充市| 荥阳市| 墨江| 桂平市| 衡山县| 合水县| 崇文区| 株洲市| 左权县| 九寨沟县| 囊谦县| 察哈| 大姚县| 渝中区|