HashMap裡的hash indexFor方法

2021-06-26 12:28:27 字數 1844 閱讀 9858

hash和indexfor方法屬於hashmap類,為什麼jdk開發者需要使用另一種hash方法而不用鍵物件自己的hashcode方法,下面看一下hash和indexfor的源**:

/** 

* 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)

/**

* returns index for hash code h.

*/

static int indexfor(int h, int length)

在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不同,也有可能對映到相同的位置上。

HashMap 裡陣列下標如何確定?

hashmap 是典型的 key 對應 value 的介面 裡面是陣列加鍊表,當 key 的hash值衝突時 用鏈位址法解決衝突 在同乙個相同下標的table中用鍊錶的形式連線起來 在這裡就可以產生問題 key的 hash 值是怎麼來的?這樣的hash 方式有什麼好處?答 在jdk1.7 中 sta...

HashMap裡的一些知識點

hashmap裡的k v值如何計算得到索引 先看演算法如下,以jdk1.8為例 int index hash arrays.length 1 hash為key的hashcode計算得到的,為什麼hashmap的陣列長度是2的整數冪呢,因為,以初始長度為16為例,16 1 15,15的二進位制數字00...

HashMap以及跟HashMap相關的內容

hashmap相信大家都用過,是以這樣的格式儲存的。其實內部真正用於儲存的是entry的陣列table 桶 下面就是源 了已經標註出來了 emprty table是個空表,用於是初始化時使用的。default load factor是負載因子,default initial capacity是初始化...