1.JDK1.8以前 HashMap = 數組(O(1))+ 單向鏈表(O(n))node
2.JDK1.8以後 HashMap = 數組(O(1))+ 單向鏈表(O(n))+ 紅黑樹(O(log n) 算法
1.默認初始化數組容量大小是16。數組
2.數組擴容恰好是2的次冪。安全
3.默認的加載因子是0.75。markdown
4.鏈表長度超過8時將鏈表轉化成紅黑樹結構。 5.紅黑樹節點數減小到6的時候退化成鏈表。數據結構
以上幾個數字關係,又爲何是上邊的幾個數字接下來一個個分析。多線程
①計算桶的位置,根據key的hashcode求出hash值,位置index = hash%length。app
②判斷是否達到擴容條件,threshold=DEFAULT_INITIAL_CAPACITY * loadFactor(16*0.75=12)大於這個閥門值就須要擴容,不然下一步。less
③判斷桶位置是否爲空,若是爲空直接在數據插入數據。若是不爲空,下一步。dom
④判斷是鏈表仍是紅黑樹,鏈表是否到達轉化紅黑樹,當前鏈表節點數<=8,插入節點;若是是紅黑樹插入節點,不然下一步。
⑤鏈表轉化成紅黑樹,插入節點。
⑥插入節點後計算當前size是否須要擴容,若是大於閥門值須要擴容resize。
/**
* Implements Map.put and related methods
*
* @param hash hash for key
* @param key the key
* @param value the value to put
* @param onlyIfAbsent if true, don't change existing value
* @param evict if false, the table is in creation mode.
* @return previous value, or null if none
*/
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.8的HashMap的get調用關鍵方法源碼。
①計算桶的位置,根據key的hashcode求出hash值,位置index = hash%length。
②不管是數值,鏈表仍是紅黑樹,for循環判斷hash值衝突就比對key是否相等,相等就返回對應的value。
/**
* Implements Map.get and related methods
*
* @param hash hash for key
* @param key the key
* @return the node, or null if none
*/
final Node<K,V> getNode(int hash, Object key) {
Node<K,V>[] tab; Node<K,V> first, e; int n; K k;
if ((tab = table) != null && (n = tab.length) > 0 &&
(first = tab[(n - 1) & hash]) != null) {
if (first.hash == hash && // always check first node
((k = first.key) == key || (key != null && key.equals(k))))
return first;
if ((e = first.next) != null) {
if (first instanceof TreeNode)
return ((TreeNode<K,V>)first).getTreeNode(hash, key);
do {
if (e.hash == hash &&
((k = e.key) == key || (key != null && key.equals(k))))
return e;
} while ((e = e.next) != null);
}
}
return null;
}
複製代碼
以上是JDK1.8的HashMap的put調用關鍵方法源碼。
①數組內存連續塊分配,效率體現查詢更快。HashMap中用做查找數組桶的位置,利用元素的key的hash值對數組長度取模獲得。
②鏈表效率體現增長和刪除。HashMap中鏈表是用來解決hash衝突,增刪空間消耗平衡。
擴展: 爲何不是ArrayList而是使用Node<K,V>[] tab?由於ArrayList的擴容機制是1.5倍擴容,而HashMap擴容是2的次冪。
static final int hash(Object key) {
int h;
return (key == null) ? 0 : (h = key.hashCode()) ^ (h >>> 16);
}
複製代碼
代碼意思是hash = hashcode的高16位異化低16位,而不是直接hashcode。
index = (n - 1) & hash
複製代碼
思想:
一是,爲了減小hash衝突使用hash%length計算,求模計算保證了獲得的結果必定在0-length範圍以內。
二是,爲了提升運算速度,模運算比不上位運算,當n是2的次冪才知足hash%length == (n-1)&hash。
肯定公式中(n-1)符合最優等式,剩下考慮hash值的最優,hash值這個因子考慮影響結果儘量不衝突。
由於計算速度體如今位運算上,條件n是2的次冪,那麼n-1的換算成二進制前邊都是連續的0,後邊都是連續的1,。好比n=16,則n-1=15,15的二進制1111。hash & 1111 = 只要關注的hash的二進制的最後四位數進行&運算。
擴展: hashcode與equals相等判斷對比: 兩個key的hashcode相等,key不必定equals。 兩個key的equals,hashcode必定相等。
思想:
上邊問題不是兩個獨立問題而是相互相關,目的儘可能減小衝突前提提升空間利用率和減小查詢成本的折中。
加載因子決定了HashMap的擴容的閥門值,若是桶是16,那麼擴容值16* 0.75=12,也就是12的時候就要考慮擴容,還有4個沒有被利用到,犧牲的空間。若是加載因子是1,空間利用率高,可是查詢速度變慢。
原理:
權衡依據是以上狀況符合泊松分佈(一種統計與機率學裏常見到的離散機率分佈,適合於描述單位時間(或空間)內隨機事件發生的次數),用0.75做爲加載因子,每一個碰撞位置的鏈表長度超過8個機率很是低,少於千萬分之一。
源碼說明:
* Because TreeNodes are about twice the size of regular nodes, we
* use them only when bins contain enough nodes to warrant use
* (see TREEIFY_THRESHOLD). And when they become too small (due to
* removal or resizing) they are converted back to plain bins. In
* usages with well-distributed user hashCodes, tree bins are
* rarely used. Ideally, under random hashCodes, the frequency of
* nodes in bins follows a Poisson distribution
* (http://en.wikipedia.org/wiki/Poisson_distribution) with a
* parameter of about 0.5 on average for the default resizing
* threshold of 0.75, although with a large variance because of
* resizing granularity. Ignoring variance, the expected
* occurrences of list size k are (exp(-0.5) * pow(0.5, k) /
* factorial(k)). The first values are:
*
* 0: 0.60653066
* 1: 0.30326533
* 2: 0.07581633
* 3: 0.01263606
* 4: 0.00157952
* 5: 0.00015795
* 6: 0.00001316
* 7: 0.00000094
* 8: 0.00000006
* more: less than 1 in ten million
複製代碼
擴展:
爲何不一開始選擇紅黑樹?
紅黑樹近乎於平衡二叉樹,結構適合均勻分佈節點,減小樹的深度像鏈表長度狀況。緣由主要是插入效率上,紅黑樹增長節點極可能須要進行左旋,右旋,着色操做,這些時間效率並無鏈表形式高。
1)選擇不可變的對象,好比字符串或int類型。
2)若是要用一個自定義實體類做爲key:
①類添加final修飾符,保證類不被繼承。
②保證全部成員變量必須私有,而且加上final修飾。
③不提供改變成員變量的方法,包括setter。
④經過構造器初始化全部成員,進行深拷貝(deep copy)。
public int hashCode() {
int h = hash;
if (h == 0 && value.length > 0) {
char val[] = value;
for (int i = 0; i < value.length; i++) {
h = 31 * h + val[i];
}
hash = h;
}
return h;
}
複製代碼
哈希計算公式:s[0]31^(n-1) + s[1]31^(n-2) + … + s[n-1]
①多線程擴容,引發的死循環問題(jdk1.8中,死循環問題已經解決)。
②多線程put的時候可能致使元素丟失。
③put非null元素後get出來的倒是null。
①HashMap並非線程安全,要實現線程安全能夠用Collections.synchronizedMap(m)獲取一個線程安全的HashMap。
②CurrentHashMap和HashTable是線程安全的。CurrentHashMap使用分段鎖技術,要操做節點先獲取段鎖,在修改節點。
①ArrayMap數據結構是兩個數組,一個存放hash值,另外一個存放key和value。
②根據key的hash值利用二分查找在hash數組中找出index。
③根據index在key-value數組中對應位置查找,若是不相等認爲衝突了,會以key爲中心,分別上下展開,逐一查找。
優點,數據量少時(少於1000)相比HashMap更節省內存。劣勢,刪除和插入時效率要比HashMap要低。