HashMap源代码深入剖析
1. 概述
首先從一個例子來開始HashMap的學習
public class Test {public static void main(String[] args) {Map<String, Integer> map = new HashMap<String, Integer>();map.put("語文", 1);map.put("數學", 2);map.put("英語", 3);map.put("歷史", 4);map.put("政治", 5);map.put("地理", 6);map.put("生物", 7);map.put("化學", 8);for (Map.Entry<String, Integer> entry : map.entrySet()) {System.out.println(entry.getKey() + ": " + entry.getValue());}} }?程序的運行結果:
政治: 5 生物: 7 歷史: 4 數學: 2 化學: 8 語文: 1 英語: 3 地理: 6發生了什么呢?下面是一個大致的結構,希望我們對HashMap的結構有一個感性的認識:
補充:
hash值對16取模的結果:
831312%16=0
828410%16=10
682778%16=10
從圖中可以看出:?
(01)HashMap繼承于AbstractMap類,實現了Map接口。Map是"key-value鍵值對"接口,AbstractMap實現了"鍵值對"的通用函數接口。
(02)HashMap是通過"拉鏈法"實現的哈希表。它包括幾個重要的成員變量:table, size, threshold, loadFactor, modCount。
table是一個Node[]數組類型,而Node(7中叫Entry)實際上就是一個單向鏈表。哈希表的"key-value鍵值對"都是存儲在Node數組中的。
size是HashMap的大小,它是HashMap保存的鍵值對的數量。
threshold是HashMap的閾值,用于判斷是否需要調整HashMap的容量。threshold的值="容量*加載因子",當HashMap中存儲數據的數量達到threshold時,就需要將HashMap的容量加倍。
loadFactor就是加載因子。
modCount是用來實現fail-fast機制的。
在官方文檔中是這樣描述HashMap的:
Hash table based implementation of the Map interface. This implementation provides all of the optional map operations, and permits null values and the null key. (The HashMap class is roughly equivalent to Hashtable, except that it is unsynchronized and permits nulls.) This class makes no guarantees as to the order of the map; in particular, it does not guarantee that the order will remain constant over time.幾個關鍵的信息:基于Map接口實現、允許null鍵/值、非同步、不保證有序、也不保證序不隨時間變化。
2. 影響HashMap實例性能的兩個參數
在HashMap中有兩個很重要的參數會影響HashMap的性能,初始容量(initial capacity)和負載因子(Load factor)
The capacity is the number of buckets in the hash table, and the initial capacity is simply the capacity at the time the hash table is created. The load factor is a measure of how full the hash table is allowed to get before its capacity is automatically increased. When the number of entries in the hash table exceeds the product of the load factor and the current capacity, the hash table is rehashed (that is, internal data structures are rebuilt) so that the hash table has approximately twice the number of buckets.hashMap 的實例有兩個參數影響其性能:"初始容量" 和 "加載因子"。容量是哈希表中桶的數量,初始容量只是哈希表在創建時的容量。加載因子是哈希表在其容量自動增加之前可以達到多滿的一種尺度。當哈希表中的條目數超出了加載因子與當前容量的乘積時,則要對該哈希表進行rehash操作(即重建內部數據結構),從而哈希表將具有大約兩倍的桶數。
通常,默認加載因子是0.75, 這是在時間和空間成本上尋求一種折衷。加載因子過高雖然減少了空間開銷,但同時也增加了查詢成本(在大多數 HashMap 類的操作中,包括get 和put操作,都反映了這一點)。在設置初始容量時應該考慮到映射中所需的條目數及其加載因子,以便最大限度地減少rehash操作次數。如果初始容量大于最大條目數除以加載因子,則不會發生 rehash 操作。
3. put函數的實現
put函數大致的思路為:
(1)對key的hashCode()做hash,然后再計算index;
(2)如果沒碰撞直接放到bucket里;
(3)如果碰撞了,以鏈表的形式存在buckets后;
(4)如果碰撞導致鏈表過長(大于等于TREEIFY_THRESHOLD),就把鏈表轉換成紅黑樹;
(5)如果節點已經存在就替換old value(保證key的唯一性)
(6)如果bucket滿了(超過load factor*current capacity),就要resize。
具體代碼的實現如下:
public V put(K key, V value) {// 對key的hashCode()做hashreturn putVal(hash(key), key, value, false, true); }final V putVal(int hash, K key, V value, boolean onlyIfAbsent,boolean evict) {Node<K,V>[] tab; Node<K,V> p; int n, i;// tab為空則創建if ((tab = table) == null || (n = tab.length) == 0)n = (tab = resize()).length;// 計算index,并對null做處理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 keyV oldValue = e.value;if (!onlyIfAbsent || oldValue == null)e.value = value;afterNodeAccess(e);return oldValue;}}++modCount;// 超過load factor*current capacity,resizeif (++size > threshold)resize();afterNodeInsertion(evict);return null; }4. get函數的實現
在理解了put之后,get就很簡單了。大致思路如下:
(1)bucket里的第一個節點,直接命中;
(2)如果有沖突,則通過key.equals(k)去查找對應的entry
若為樹,則在樹中通過key.equals(k)查找,O(logn);
若為鏈表,則在鏈表中通過key.equals(k)查找,O(n)。
具體代碼的實現如下:
public V get(Object key) {Node<K,V> e;return (e = getNode(hash(key), key)) == null ? null : e.value; }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) {// 在樹中getif (first instanceof TreeNode)return ((TreeNode<K,V>)first).getTreeNode(hash, key);// 在鏈表中getdo {if (e.hash == hash &&((k = e.key) == key || (key != null && key.equals(k))))return e;} while ((e = e.next) != null);}}return null; }5. hash函數的實現
在get和put的過程中,計算下標時,先對hashCode進行hash操作,然后再通過hash值進一步計算下標,
在對hashCode()計算hash時具體實現是這樣的:
?
static final int hash(Object key) {int h;return (key == null) ? 0 : (h = key.hashCode()) ^ (h >>> 16); }?
如下圖所示:
可以看到這個函數大概的作用就是:高16bit不變,低16bit和高16bit做了一個異或。其中代碼注釋是這樣寫的:
?
Computes key.hashCode() and spreads (XORs) higher bits of hash to lower. Because the table uses power-of-two masking, sets of hashes that vary only in bits above the current mask will always collide. (Among known examples are sets of Float keys holding consecutive whole numbers in small tables.) So we apply a transform that spreads the impact of higher bits downward. There is a tradeoff between speed, utility, and quality of bit-spreading. Because many common sets of hashes are already reasonably distributed (so don't benefit from spreading), and because we use trees to handle large sets of collisions in bins, we just XOR some shifted bits in the cheapest possible way to reduce systematic lossage, as well as to incorporate impact of the highest bits that would otherwise never be used in index calculations because of table bounds.?
在設計hash函數時,因為目前的table長度n為2的冪,而計算下標的時候,是這樣實現的(使用&位操作,而非%求余):
(n - 1) & hash設計者認為這方法很容易發生碰撞。為什么這么說呢?不妨思考一下,在n - 1為15(1111)時,其實散列真正生效的只是低4bit的有效位,當然容易碰撞了。
因此,設計者想了一個顧全大局的方法(綜合考慮了速度、作用、質量),就是把高16bit和低16bit異或了一下。設計者還解釋到因為現在大多數的hashCode的分布已經很不錯了,就算是發生了碰撞也用O(logn)的tree去做了。僅僅異或一下,既減少了系統的開銷,也不會造成因為高位沒有參與下標的計算(table長度比較小時),從而引起的碰撞。
之前已經提過,在獲取HashMap的元素時,基本分兩步:
在Java 8之前的實現中是用鏈表解決沖突的,在產生碰撞的情況下,進行get時,兩步的時間復雜度是O(1)+O(n)。因此,當碰撞很厲害的時候n很大,O(n)的速度顯然是影響速度的。
因此在Java 8中,利用紅黑樹替換鏈表,這樣復雜度就變成了O(1)+O(logn)了,這樣在n很大的時候,能夠比較理想的解決這個問題,在Java 8:HashMap的性能提升一文中有性能測試的結果。
6. resize的實現
當put時,如果發現目前的bucket占用程度已經超過了Load Factor所希望的比例,那么就會發生resize。在resize的過程,簡單的說就是把bucket擴充為2倍,之后重新計算index,把節點再放到新的bucket中。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.
大致意思就是說,當超過限制的時候會resize,然而又因為我們使用的是2次冪的擴展(指長度擴為原來2倍),所以,元素的位置要么是在原位置,要么是在原位置再移動2次冪的位置。
怎么理解呢?例如我們從16擴展為32時,具體的變化如下所示:
因此元素在重新計算hash之后,因為n變為2倍,那么n-1的mask范圍在高位多1bit(紅色),因此新的index就會發生這樣的變化:
因此,我們在擴充HashMap的時候,不需要重新計算hash,只需要看看原來的hash值新增的那個bit是1還是0就好了,是0的話索引沒變,是1的話索引變成“原索引+oldCap”。可以看看下圖為16擴充為32的resize示意圖:
這個設計確實非常的巧妙,既省去了重新計算hash值的時間,而且同時,由于新增的1bit是0還是1可以認為是隨機的,因此resize的過程,均勻的把之前的沖突的節點分散到新的bucket了。
下面是代碼的具體實現:
final Node<K,V>[] resize() {Node<K,V>[] oldTab = table;int oldCap = (oldTab == null) ? 0 : oldTab.length;int oldThr = threshold;int newCap, newThr = 0;if (oldCap > 0) {// 超過最大值就不再擴充了,就只好隨你碰撞去吧if (oldCap >= MAXIMUM_CAPACITY) {threshold = Integer.MAX_VALUE;return oldTab;}// 沒超過最大值,就擴充為原來的2倍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 thresholdnewCap = oldThr;else { // zero initial threshold signifies using defaultsnewCap = DEFAULT_INITIAL_CAPACITY;newThr = (int)(DEFAULT_LOAD_FACTOR * DEFAULT_INITIAL_CAPACITY);}// 計算新的resize上限if (newThr == 0) {float ft = (float)newCap * loadFactor;newThr = (newCap < MAXIMUM_CAPACITY && ft < (float)MAXIMUM_CAPACITY ?(int)ft : Integer.MAX_VALUE);}threshold = newThr;@SuppressWarnings({"rawtypes","unchecked"})Node<K,V>[] newTab = (Node<K,V>[])new Node[newCap];table = newTab;if (oldTab != null) {// 把每個bucket都移動到新的buckets中for (int j = 0; j < oldCap; ++j) {Node<K,V> e;if ((e = oldTab[j]) != null) {oldTab[j] = null;if (e.next == null)newTab[e.hash & (newCap - 1)] = e;else if (e instanceof TreeNode)((TreeNode<K,V>)e).split(this, newTab, j, oldCap);else { // preserve orderNode<K,V> loHead = null, loTail = null;Node<K,V> hiHead = null, hiTail = null;Node<K,V> next;do {next = e.next;// 原索引if ((e.hash & oldCap) == 0) {if (loTail == null)loHead = e;elseloTail.next = e;loTail = e;}// 原索引+oldCapelse {if (hiTail == null)hiHead = e;elsehiTail.next = e;hiTail = e;}} while ((e = next) != null);// 原索引放到bucket里if (loTail != null) {loTail.next = null;newTab[j] = loHead;}// 原索引+oldCap放到bucket里if (hiTail != null) {hiTail.next = null;newTab[j + oldCap] = hiHead;}}}}}return newTab; }7. 總結
1. 什么時候會使用HashMap?他有什么特點?
是基于Map接口的實現,存儲鍵值對時,它可以接收null的鍵值,是非同步的,HashMap存儲著Entry(hash, key, value, next)對象。
2. 你知道HashMap的工作原理嗎?
通過hash的方法,通過put和get存儲和獲取對象。存儲對象時,我們將K/V傳給put方法時,它調用hashCode計算hash從而得到bucket位置,進一步存儲,HashMap會根據當前 bucket的占用情況自動調整容量(超過Load Facotr則resize為原來的2倍)。獲取對象時,我們將K傳給get,它調用hashCode計算hash從而得到bucket位置,并進一步調 用equals()方法確定鍵值對。如果發生碰撞的時候,Hashmap通過鏈表將產生碰撞沖突的元素組織起來,在Java 8中,如果一個bucket中碰撞沖突的元素超過某個限制(默認是8),則使用紅黑樹來替換鏈表,從而提高速度。
3. 你知道get和put的原理嗎?equals()和hashCode()的都有什么作用?
通過對key的hashCode()進行hashing,并計算下標( n-1 & hash),從而獲得buckets的位置。如果產生碰撞,則利用key.equals()方法去鏈表或樹中去查找對應的節點
4. 你知道hash的實現嗎?為什么要這樣實現?
在Java 1.8的實現中,是通過hashCode()的高16位異或低16位實現的:(h = k.hashCode()) ^ (h >>> 16),主要是從速度、功效、質量來考慮的,這么做可以在bucket的n比較小的時候,也能保證考慮到高低bit都參與到hash的計算中,同時不會有太大的開銷。
5. 如果HashMap的大小超過了負載因子(load factor)定義的容量,怎么辦?
如果超過了負載因子(默認0.75),則會重新resize一個原來長度兩倍的HashMap,并且重新調用hash方法。
關于Java集合的小抄中是這樣描述的:
以Entry[]數組實現的哈希桶數組,用Key的哈希值取模桶數組的大小可得到數組下標。插入元素時,如果兩條Key落在同一個桶(比如哈希值1和17取模16后都屬于第一個哈希桶),Entry用一個next屬性實現多個Entry以單向鏈表存放,后入桶的Entry將next指向桶當前的Entry。查找哈希值為17的key時,先定位到第一個哈希桶,然后以鏈表遍歷桶里所有元素,逐個比較其key值。當Entry數量達到桶數量的75%時(很多文章說使用的桶數量達到了75%,但看代碼不是),會成倍擴容桶數組,并重新分配所有原來的Entry,所以這里也最好有個預估值。取模用位運算(hash & (arrayLength-1))會比較快,所以數組的大小永遠是2的N次方, 你隨便給一個初始值比如17會轉為32。默認第一次放入元素時的初始值是16。iterator()時順著哈希桶數組來遍歷,看起來是個亂序。在JDK8里,新增默認為8的閥值,當一個桶里的Entry超過閥值,就不以單向鏈表而以紅黑樹來存放以加快Key的查找速度。參考:
http://yikun.github.io/2015/04/01/Java-HashMap%E5%B7%A5%E4%BD%9C%E5%8E%9F%E7%90%86%E5%8F%8A%E5%AE%9E%E7%8E%B0/
總結
以上是生活随笔為你收集整理的HashMap源代码深入剖析的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: mxGraph实现按住ctrl键盘拖动图
- 下一篇: 怎么调试EXC_BAD_ACCESS错误