Jdk1.8 HashMap 基礎
阿新 • • 發佈:2018-11-22
HashMap 特性
- key,value可以為空
- 執行緒不安全
- 支援快速失敗(在for迴圈中操作remove,put方法時會報ConcurrentModifyException)
HashMap 的幾個基本屬性值
- loadFactor: 載入因子,loadFactor越大,hashmap的空間利用率越大,反之空間利用率越低.預設值為0.75.
- threshold: 容量閾值,超過該值會觸發hashMap的擴容操作.
- capacity: 容量值為2的n的次方值預設值為16
- size: hashMap中包含的node個數
HashMap 的put過程
- 計算index值 index=(n-1)&hash
- 拿到index確定該位置下是否有元素存在,如果不存在則建立一個新的元素賦給該index下,方法結束.
- 如果存在則判斷key與hash值與傳入的key,hash是否一致,如果一致則根據傳入的ifAbsent值是否修改value的值.方法結束
- 如果key與hash不一致,則遍歷index對應的連結串列,如果連結串列中存在key和hash值與傳入的值一致則根據ifAsent值修改value值,如果不在這個的記錄,則新建一個新的記錄放在連結串列的最後
- 如果連結串列的長度超過設定的值,這會將連結串列結構資料轉化為紅黑數結構
- 如果size超過threshold值則觸發resize操作
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; }
HashMap resize 過程
/**
* Initializes or doubles table size. If null, allocates in
* accord with initial capacity target held in field threshold.
* Otherwise, because we are using power-of-two expansion, the
* elements from each bin must either stay at same index, or move
* with a power of two offset in the new table.
*
* @return the table
*/
final Node<K,V>[] resize() {
Node<K,V>[] oldTab = table;
int oldCap = (oldTab == null) ? 0 : oldTab.length;
int oldThr = threshold;
int newCap, newThr = 0;
//計算出Threshold
if (oldCap > 0) {
// 如果老的容量大於等於最大容量則Threshold為整型最大值,並且直接返回hashTable,不進 行擴容
if (oldCap >= MAXIMUM_CAPACITY) {
threshold = Integer.MAX_VALUE;
return oldTab;
}
// 設定新容量為老容量的兩倍且小於最大容量值,並且老容量大於等於預設容量,則新Threshold為之前的兩倍
else if ((newCap = oldCap << 1) < MAXIMUM_CAPACITY &&
oldCap >= DEFAULT_INITIAL_CAPACITY)
newThr = oldThr << 1; // double threshold
}
else if (oldThr > 0) // initial capacity was placed in threshold
newCap = oldThr;
// 新容量為預設值,threshold為容量的0.75
else { // zero initial threshold signifies using defaults
newCap = DEFAULT_INITIAL_CAPACITY;
newThr = (int)(DEFAULT_LOAD_FACTOR * DEFAULT_INITIAL_CAPACITY);
}
if (newThr == 0) {
float ft = (float)newCap * loadFactor;
newThr = (newCap < MAXIMUM_CAPACITY && ft < (float)MAXIMUM_CAPACITY ?
(int)ft : Integer.MAX_VALUE);
}
//設定threshold值
threshold = newThr;
@SuppressWarnings({"rawtypes","unchecked"})
Node<K,V>[] newTab = (Node<K,V>[])new Node[newCap];
table = newTab;
if (oldTab != null) {
for (int j = 0; j < oldCap; ++j) {
Node<K,V> e;
if ((e = oldTab[j]) != null) {
// 將hashTable中j位置的值置空
oldTab[j] = null;
// 如果e的next為空,意味著該節點上只有一個元素,不是一條連結串列
if (e.next == null)
newTab[e.hash & (newCap - 1)] = e;
// 如果e是一個TreeNode則走紅黑樹的流程
else if (e instanceof TreeNode)
((TreeNode<K,V>)e).split(this, newTab, j, oldCap);
// 如果e的next不為空,意味這改節點上是一條連結串列結構
else { // preserve order
Node<K,V> loHead = null, loTail = null;
Node<K,V> hiHead = null, hiTail = null;
Node<K,V> next;
do {
next = e.next;
// e.hash值得最高位為0無需變化
if ((e.hash & oldCap) == 0) {
if (loTail == null)
loHead = e;
else
loTail.next = e;
loTail = e;
}
// e.hash值最高位為1,位置變為之前位置加上oldCap
else {
if (hiTail == null)
hiHead = e;
else
hiTail.next = e;
hiTail = e;
}
} while ((e = next) != null);
if (loTail != null) {
loTail.next = null;
newTab[j] = loHead;
}
if (hiTail != null) {
hiTail.next = null;
newTab[j + oldCap] = hiHead;
}
}
}
}
}
return newTab;
}
問題1: 為什麼用(n-1)&hash來計算資料下標值?
這樣可以減少hash碰撞.因為n的值是2的n次方,所以除最高位是1外其他位都是0,在與操作的時候不參與運算(任何數與0都為0).所以用n&hash會產生許多相同的值.
問題2: 在多執行緒執行put方法情況下不會死迴圈,但會有資料丟失的情況?
在多執行緒執行的情況下,如果發生hash碰撞,會發生資料覆蓋,導致資料丟失.