什么時候擴容
- jdk 1.7
- 判斷是否達到了閾值(0.75 × 數組長度)
- 同時這次put是否產生了Hash沖突
if ((size >= threshold) && (null != table[bucketIndex])) {
resize(2 * table.length); //兩倍擴容
hash = (null != key) ? hash(key) : 0;
bucketIndex = indexFor(hash, table.length);
}
final V putVal(int hash, K key, V value, boolean onlyIfAbsent,
boolean evict) {
Node<K,V>[] tab; Node<K,V> p; int n, i;
if ((tab = table) == null || (n = tab.length) == 0)
n = (tab = resize()).length;
if ((p = tab[i = (n - 1) & hash]) == null)
tab[i] = newNode(hash, key, value, null);
else {
Node<K,V> e; K k;
if (p.hash == hash &&
((k = p.key) == key || (key != null && key.equals(k))))
e = p;
else if (p instanceof TreeNode)
e = ((TreeNode<K,V>)p).putTreeVal(this, tab, hash, key, value);
else {
for (int binCount = 0; ; ++binCount) {
if ((e = p.next) == null) {
p.next = newNode(hash, key, value, null);
if (binCount >= TREEIFY_THRESHOLD - 1) // -1 for 1st
treeifyBin(tab, hash);
break;
}
if (e.hash == hash &&
((k = e.key) == key || (key != null && key.equals(k))))
break;
p = e;
}
}
if (e != null) { // existing mapping for key
V oldValue = e.value;
if (!onlyIfAbsent || oldValue == null)
e.value = value;
afterNodeAccess(e);
return oldValue;
}
}
++modCount;
if (++size > threshold) //上面先添加元素,然后再判斷是否達到了閾值
resize();
afterNodeInsertion(evict);
return null;
}
怎么擴容
- jdk1.7
- jdk1.8
- 添加元素使用尾插法
- 如果對應數組下標位是單向鏈表,將單向鏈表進行數據遷移
- 如果對應數組下標是紅黑樹,將雙向鏈表進行數據遷移(當鏈表長度超過8個時,會將單向鏈表轉換為紅黑樹,此時會維護一個雙向鏈表,用於數據遷移)
- 如果發現遷移完數據后,雙向鏈表的結構小於/等於6,會將紅黑樹重新轉換成單向鏈表
static final int UNTREEIFY_THRESHOLD = 6;
if (lc <= UNTREEIFY_THRESHOLD)
tab[index] = loHead.untreeify(map); //將雙向鏈表轉換成單鏈表
else {
tab[index] = loHead;
if (hiHead != null) // (else is already treeified)
loHead.treeify(tab); //將雙向鏈表轉換成樹
}
}
if (hiHead != null) {
if (hc <= UNTREEIFY_THRESHOLD)
tab[index + bit] = hiHead.untreeify(map);
else {
tab[index + bit] = hiHead;
if (loHead != null)
hiHead.treeify(tab);
}
}
```:
### 擴容后有什么問題(多線程環境下)
* jdk1.7
* 多線程環境下會形成環形鏈表
* jdk 1.8
* 多線程環境下會有數據丟失,因為是直接覆蓋。
### hash沖突的數據結構解決
* jdk1.7
* 產生沖突后會形成單向鏈表
* jdk 1.8
* 產生沖突后會形成單向鏈表
* 如果單向鏈表的長度大於等於8,會轉換成紅黑樹+雙向鏈表(擴容時使用),擴容后發現雙向鏈表的節點小於等於6個,則會將雙向鏈表轉換成單向鏈表,否則轉換成紅黑樹