HashMap的擴容機制---resize()

雖然在hashmap的原理裏面有這段,可是這個單獨拿出來說rehash或者resize()也是極好的。

何時擴容:當向容器添加元素的時候,會判斷當前容器的元素個數,若是大於等於閾值---即當前數組的長度乘以加載因子的值的時候,就要自動擴容啦。java

擴容(resize)就是從新計算容量,向HashMap對象裏不停的添加元素,而HashMap對象內部的數組沒法裝載更多的元素時,對象就須要擴大數組的長度,以便能裝入更多的元素。固然Java裏的數組是沒法自動擴容的,方法是使用一個新的數組代替已有的容量小的數組,就像咱們用一個小桶裝水,若是想裝更多的水,就得換大水桶。算法

咱們分析下resize的源碼,鑑於JDK1.8融入了紅黑樹,較複雜,爲了便於理解咱們仍然使用JDK1.7的代碼,好理解一些,本質上區別不大,具體區別後文再說。數組

  1. void resize(int newCapacity) {   //傳入新的容量  
  2.     Entry[] oldTable = table;    //引用擴容前的Entry數組  
  3.     int oldCapacity = oldTable.length;  
  4.     if (oldCapacity == MAXIMUM_CAPACITY) {  //擴容前的數組大小若是已經達到最大(2^30)了  
  5.         threshold = Integer.MAX_VALUE; //修改閾值爲int的最大值(2^31-1),這樣之後就不會擴容了  
  6.         return;  
  7.     }  
  8.   
  9.     Entry[] newTable = new Entry[newCapacity];  //初始化一個新的Entry數組  
  10.     transfer(newTable);                         //!!將數據轉移到新的Entry數組裏  
  11.     table = newTable;                           //HashMap的table屬性引用新的Entry數組  
  12.     threshold = (int) (newCapacity * loadFactor);//修改閾值  
  13. }  

這裏就是使用一個容量更大的數組來代替已有的容量小的數組,transfer()方法將原有Entry數組的元素拷貝到新的Entry數組裏。app

  1. void transfer(Entry[] newTable) {  
  2.     Entry[] src = table;                   //src引用了舊的Entry數組  
  3.     int newCapacity = newTable.length;  
  4.     for (int j = 0; j < src.length; j++) { //遍歷舊的Entry數組  
  5.         Entry<K, V> e = src[j];             //取得舊Entry數組的每一個元素  
  6.         if (e != null) {  
  7.             src[j] = null;//釋放舊Entry數組的對象引用(for循環後,舊的Entry數組再也不引用任何對象)  
  8.             do {  
  9.                 Entry<K, V> next = e.next;  
  10.                 int i = indexFor(e.hash, newCapacity); //!!從新計算每一個元素在數組中的位置  
  11.                 e.next = newTable[i]; //標記[1]  
  12.                 newTable[i] = e;      //將元素放在數組上  
  13.                 e = next;             //訪問下一個Entry鏈上的元素  
  14.             } while (e != null);  
  15.         }  
  16.     }  
  17. }  
  1. static int indexFor(int h, int length) {  
  2.     return h & (length - 1);  
  3. }  

文章中間部分:4、存儲實現;詳細解釋了爲何indexFor方法中要h & (length-1)優化

 

newTable[i]的引用賦給了e.next,也就是使用了單鏈表的頭插入方式,同一位置上新元素總會被放在鏈表的頭部位置;這樣先放在一個索引上的元素終會被放到Entry鏈的尾部(若是發生了hash衝突的話),這一點和Jdk1.8有區別,下文詳解。在舊數組中同一條Entry鏈上的元素,經過從新計算索引位置後,有可能被放到了新數組的不一樣位置上。this

下面舉個例子說明下擴容過程。spa

這句話是重點----hash(){return key % table.length;}方法,就是翻譯下面的一行解釋:.net

假設了咱們的hash算法就是簡單的用key mod 一下表的大小(也就是數組的長度)。翻譯

其中的哈希桶數組table的size=2, 因此key = 三、七、5,put順序依次爲 五、七、3。在mod 2之後都衝突在table[1]這裏了。這裏假設負載因子 loadFactor=1,即當鍵值對的實際大小size 大於 table的實際大小時進行擴容。接下來的三個步驟是哈希桶數組 resize成4,而後全部的Node從新rehash的過程。設計

jdk1.7擴容例圖

下面咱們講解下JDK1.8作了哪些優化。通過觀測能夠發現,咱們使用的是2次冪的擴展(指長度擴爲原來2倍),因此,

通過rehash以後,元素的位置要麼是在原位置,要麼是在原位置再移動2次冪的位置。對應的就是下方的resize的註釋。

 

[java] view plain copy

  1. /** 
  2.  * Initializes or doubles table size.  If null, allocates in 
  3.  * accord with initial capacity target held in field threshold. 
  4.  * Otherwise, because we are using power-of-two expansion, the 
  5.  * elements from each bin must either stay at same index, or move 
  6.  * with a power of two offset in the new table. 
  7.  * 
  8.  * @return the table 
  9.  */  
  10. final Node<K,V>[] resize() {  

 

看下圖能夠明白這句話的意思,n爲table的長度,圖(a)表示擴容前的key1和key2兩種key肯定索引位置的示例,圖(b)表示擴容後key1和key2兩種key肯定索引位置的示例,其中hash1是key1對應的哈希與高位運算結果。

hashMap 1.8 哈希算法例圖1

元素在從新計算hash以後,由於n變爲2倍,那麼n-1的mask範圍在高位多1bit(紅色),所以新的index就會發生這樣的變化:

hashMap 1.8 哈希算法例圖2

所以,咱們在擴充HashMap的時候,不須要像JDK1.7的實現那樣從新計算hash,只須要看看原來的hash值新增的那個bit是1仍是0就行了,是0的話索引沒變,是1的話索引變成「原索引+oldCap」,能夠看看下圖爲16擴充爲32的resize示意圖:

jdk1.8 hashMap擴容例圖

這個設計確實很是的巧妙,既省去了從新計算hash值的時間,並且同時,因爲新增的1bit是0仍是1能夠認爲是隨機的,所以resize的過程,均勻的把以前的衝突的節點分散到新的bucket了。這一塊就是JDK1.8新增的優化點。有一點注意區別,JDK1.7中rehash的時候,舊鏈表遷移新鏈表的時候,若是在新表的數組索引位置相同,則鏈表元素會倒置,可是從上圖能夠看出,JDK1.8不會倒置。有興趣的同窗能夠研究下JDK1.8的resize源碼,寫的很贊,以下:

1 final Node<K,V>[] resize() {
 2     Node<K,V>[] oldTab = table;
 3     int oldCap = (oldTab == null) ? 0 : oldTab.length;
 4     int oldThr = threshold;
 5     int newCap, newThr = 0;
 6     if (oldCap > 0) {
 7         // 超過最大值就再也不擴充了,就只好隨你碰撞去吧
 8         if (oldCap >= MAXIMUM_CAPACITY) {
 9             threshold = Integer.MAX_VALUE;
10             return oldTab;
11         }
12         // 沒超過最大值,就擴充爲原來的2倍
13         else if ((newCap = oldCap << 1) < MAXIMUM_CAPACITY &&
14                  oldCap >= DEFAULT_INITIAL_CAPACITY)
15             newThr = oldThr << 1; // double threshold
16     }
17     else if (oldThr > 0) // initial capacity was placed in threshold
18         newCap = oldThr;
19     else {               // zero initial threshold signifies using defaults
20         newCap = DEFAULT_INITIAL_CAPACITY;
21         newThr = (int)(DEFAULT_LOAD_FACTOR * DEFAULT_INITIAL_CAPACITY);
22     }
23     // 計算新的resize上限
24     if (newThr == 0) {
25 
26         float ft = (float)newCap * loadFactor;
27         newThr = (newCap < MAXIMUM_CAPACITY && ft < (float)MAXIMUM_CAPACITY ?
28                   (int)ft : Integer.MAX_VALUE);
29     }
30     threshold = newThr;
31     @SuppressWarnings({"rawtypes","unchecked"})
32         Node<K,V>[] newTab = (Node<K,V>[])new Node[newCap];
33     table = newTab;
34     if (oldTab != null) {
35         // 把每一個bucket都移動到新的buckets中
36         for (int j = 0; j < oldCap; ++j) {
37             Node<K,V> e;
38             if ((e = oldTab[j]) != null) {
39                 oldTab[j] = null;
40                 if (e.next == null)
41                     newTab[e.hash & (newCap - 1)] = e;
42                 else if (e instanceof TreeNode)
43                     ((TreeNode<K,V>)e).split(this, newTab, j, oldCap);
44                 else { // 鏈表優化重hash的代碼塊
45                     Node<K,V> loHead = null, loTail = null;
46                     Node<K,V> hiHead = null, hiTail = null;
47                     Node<K,V> next;
48                     do {
49                         next = e.next;
50                         // 原索引
51                         if ((e.hash & oldCap) == 0) {
52                             if (loTail == null)
53                                 loHead = e;
54                             else
55                                 loTail.next = e;
56                             loTail = e;
57                         }
58                         // 原索引+oldCap
59                         else {
60                             if (hiTail == null)
61                                 hiHead = e;
62                             else
63                                 hiTail.next = e;
64                             hiTail = e;
65                         }
66                     } while ((e = next) != null);
67                     // 原索引放到bucket裏
68                     if (loTail != null) {
69                         loTail.next = null;
70                         newTab[j] = loHead;
71                     }
72                     // 原索引+oldCap放到bucket裏
73                     if (hiTail != null) {
74                         hiTail.next = null;
75                         newTab[j + oldCap] = hiHead;
76                     }
77                 }
78             }
79         }
80     }
81     return newTab;
82 }
相關文章
相關標籤/搜索