這篇文章主要介紹“HashMap的底層實現(xiàn)原理”,在日常操作中,相信很多人在HashMap的底層實現(xiàn)原理問題上存在疑惑,小編查閱了各式資料,整理出簡單好用的操作方法,希望對大家解答”HashMap的底層實現(xiàn)原理”的疑惑有所幫助!接下來,請跟著小編一起來學(xué)習(xí)吧!
成都創(chuàng)新互聯(lián)公司,為您提供重慶網(wǎng)站建設(shè)公司、成都網(wǎng)站制作公司、網(wǎng)站營銷推廣、網(wǎng)站開發(fā)設(shè)計,對服務(wù)發(fā)電機維修等多個行業(yè)擁有豐富的網(wǎng)站建設(shè)及推廣經(jīng)驗。成都創(chuàng)新互聯(lián)公司網(wǎng)站建設(shè)公司成立于2013年,提供專業(yè)網(wǎng)站制作報價服務(wù),我們深知市場的競爭激烈,認(rèn)真對待每位客戶,為客戶提供賞心悅目的作品。 與客戶共同發(fā)展進步,是我們永遠(yuǎn)的責(zé)任!
/** * Basic hash bin node, used for most entries. (See below for * TreeNode subclass, and in LinkedHashMap for its Entry subclass.) */ /** Node是hash基礎(chǔ)的節(jié)點,是單向鏈表,實現(xiàn)了Map.Entry接口 */static class Nodeimplements Map.Entry { final int hash; final K key; V value; Node next; //構(gòu)造函數(shù) Node(int hash, K key, V value, Node next) { this.hash = hash; this.key = key; this.value = value; this.next = next; } public final K getKey() { return key; } public final V getValue() { return value; } public final String toString() { return key + "=" + value; } public final int hashCode() { return Objects.hashCode(key) ^ Objects.hashCode(value); } public final V setValue(V newValue) { V oldValue = value; value = newValue; return oldValue; } public final boolean equals(Object o) { if (o == this) return true; if (o instanceof Map.Entry) { Map.Entry,?> e = (Map.Entry,?>)o; if (Objects.equals(key, e.getKey()) && Objects.equals(value, e.getValue())) return true; } return false; }}復(fù)制代碼
TreeNode 是紅黑樹的數(shù)據(jù)結(jié)構(gòu)。
/** * Entry for Tree bins. Extends LinkedHashMap.Entry (which in turn * extends Node) so can be used as extension of either regular or * linked node. */ static final class TreeNodeextends LinkedHashMap.Entry { TreeNode parent; // red-black tree links TreeNode left; TreeNode right; TreeNode prev; // needed to unlink next upon deletion boolean red; TreeNode(int hash, K key, V val, Node next) { super(hash, key, val, next); } /** * Returns root of tree containing this node. */ final TreeNode root() { for (TreeNode r = this, p;;) { if ((p = r.parent) == null) return r; r = p; } }復(fù)制代碼
public class HashMapextends AbstractMap implements Map , Cloneable, Serializable {復(fù)制代碼
繼承了抽象的map,實現(xiàn)了Map接口,并且進行了序列化。
在類里還有基礎(chǔ)的變量
/** * The default initial capacity - MUST be a power of two. * 默認(rèn)初始容量 16 - 必須是2的冪 */static final int DEFAULT_INITIAL_CAPACITY = 1 << 4; // aka 16/** * The maximum capacity, used if a higher value is implicitly specified * by either of the constructors with arguments. * MUST be a power of two <= 1<<30. * 最大容量 2的30次方 */static final int MAXIMUM_CAPACITY = 1 << 30;/** * The load factor used when none specified in constructor. * 默認(rèn)加載因子,用來計算threshold */ static final float DEFAULT_LOAD_FACTOR = 0.75f;/** * The bin count threshold for using a tree rather than list for a * bin. Bins are converted to trees when adding an element to a * bin with at least this many nodes. The value must be greater * than 2 and should be at least 8 to mesh with assumptions in * tree removal about conversion back to plain bins upon * shrinkage. * 鏈表轉(zhuǎn)成樹的閾值,當(dāng)桶中鏈表長度大于8時轉(zhuǎn)成樹 * threshold = capacity * loadFactor */static final int TREEIFY_THRESHOLD = 8;/** * The bin count threshold for untreeifying a (split) bin during a * resize operation. Should be less than TREEIFY_THRESHOLD, and at * most 6 to mesh with shrinkage detection under removal. * 進行resize操作時,若桶中數(shù)量少于6則從樹轉(zhuǎn)成鏈表 */static final int UNTREEIFY_THRESHOLD = 6;/** * The smallest table capacity for which bins may be treeified. * (Otherwise the table is resized if too many nodes in a bin.) * Should be at least 4 * TREEIFY_THRESHOLD to avoid conflicts * between resizing and treeification thresholds. * 桶中結(jié)構(gòu)轉(zhuǎn)化為紅黑樹對應(yīng)的table的最小大小 * 當(dāng)需要將解決 hash 沖突的鏈表轉(zhuǎn)變?yōu)榧t黑樹時, * 需要判斷下此時數(shù)組容量, * 若是由于數(shù)組容量太?。ㄐ∮凇IN_TREEIFY_CAPACITY ) * 導(dǎo)致的 hash 沖突太多,則不進行鏈表轉(zhuǎn)變?yōu)榧t黑樹操作, * 轉(zhuǎn)為利用 resize() 函數(shù)對 hashMap 擴容 */static final int MIN_TREEIFY_CAPACITY = 64;/** * The table, initialized on first use, and resized as * necessary. When allocated, length is always a power of two. * (We also tolerate length zero in some operations to allow * bootstrapping mechanics that are currently not needed.) * 保存Node節(jié)點的數(shù)組 * 該表在首次使用時初始化,并根據(jù)需要調(diào)整大小。 分配時, * 長度始終是2的冪。 */transient Node [] table;/** * Holds cached entrySet(). Note that AbstractMap fields are used * for keySet() and values(). * 存放具體元素的集 */transient Set > entrySet;/** * The number of key-value mappings contained in this map. * 記錄 hashMap 當(dāng)前存儲的元素的數(shù)量 */transient int size;/** * The number of times this HashMap has been structurally modified * Structural modifications are those that change the number of mappings in * the HashMap or otherwise modify its internal structure (e.g., * rehash). This field is used to make iterators on Collection-views of * the HashMap fail-fast. (See ConcurrentModificationException). * 每次更改map結(jié)構(gòu)的計數(shù)器 */transient int modCount;/** * The next size value at which to resize (capacity * load factor). * 臨界值 當(dāng)實際大小(容量*填充因子)超過臨界值時,會進行擴容 * @serial */// (The javadoc description is true upon serialization.// Additionally, if the table array has not been allocated, this// field holds the initial array capacity, or zero signifying// DEFAULT_INITIAL_CAPACITY.)int threshold;/** * The load factor for the hash table. * 負(fù)載因子:要調(diào)整大小的下一個大小值(容量*加載因子)。 * @serial */final float loadFactor;復(fù)制代碼
我們再看看構(gòu)造方法
/** * Constructs an empty HashMap with the specified initial * capacity and the default load factor (0.75). * * @param initialCapacity the initial capacity. * @throws IllegalArgumentException if the initial capacity is negative. * 傳入初始容量大小,使用默認(rèn)負(fù)載因子值 來初始化HashMap對象 */public HashMap(int initialCapacity) { this(initialCapacity, DEFAULT_LOAD_FACTOR);}/** * Constructs an empty HashMap with the default initial capacity * (16) and the default load factor (0.75). * 默認(rèn)容量和負(fù)載因子 */public HashMap() { this.loadFactor = DEFAULT_LOAD_FACTOR; // all other fields defaulted}/** * Constructs an empty HashMap with the specified initial * capacity and load factor. * * @param initialCapacity the initial capacity * @param loadFactor the load factor * @throws IllegalArgumentException if the initial capacity is negative * or the load factor is nonpositive * 傳入初始容量大小和負(fù)載因子 來初始化HashMap對象 */public HashMap(int initialCapacity, float loadFactor) { // 初始容量不能小于0,否則報錯 if (initialCapacity < 0) throw new IllegalArgumentException("Illegal initial capacity: " + initialCapacity); // 初始容量不能大于最大值,否則為最大值 if (initialCapacity > MAXIMUM_CAPACITY) initialCapacity = MAXIMUM_CAPACITY; //負(fù)載因子不能小于或等于0,不能為非數(shù)字 if (loadFactor <= 0 || Float.isNaN(loadFactor)) throw new IllegalArgumentException("Illegal load factor: " + loadFactor); // 初始化負(fù)載因子 this.loadFactor = loadFactor; // 初始化threshold大小 this.threshold = tableSizeFor(initialCapacity);}/** * Returns a power of two size for the given target capacity. * 找到大于或等于 cap 的最小2的整數(shù)次冪的數(shù) */static final int tableSizeFor(int cap) { int n = cap - 1; n |= n >>> 1; n |= n >>> 2; n |= n >>> 4; n |= n >>> 8; n |= n >>> 16; return (n < 0) ? 1 : (n >= MAXIMUM_CAPACITY) ? MAXIMUM_CAPACITY : n + 1;}復(fù)制代碼
在這源碼中,loadFactor負(fù)載因子是一個非常重要的參數(shù),因為他能夠反映HashMap桶數(shù)組的使用情況, 這樣的話,HashMap的時間復(fù)雜度就會出現(xiàn)不同的改變。
當(dāng)這個負(fù)載因子屬于低負(fù)載因子的時候,HashMap所能夠容納的鍵值對數(shù)量就是偏少的,擴容后,重新將鍵值對 存儲在桶數(shù)組中,鍵與鍵之間產(chǎn)生的碰撞會下降,鏈表的長度也會隨之變短。
但是如果增加負(fù)載因子當(dāng)這個負(fù)載因子大于1的時候,HashMap所能夠容納的鍵值對就會變多,這樣碰撞就會增加, 這樣的話鏈表的長度也會增加,一般情況下負(fù)載因子我們都不會去修改。都是默認(rèn)的0.75。加q群:479499375,可獲取一份Java進階學(xué)習(xí)資料包,有(Java工程化、分布式架構(gòu)、高并發(fā)、高性能、深入淺出、微服務(wù)架構(gòu)、Spring、MyBatis、Netty、源碼分析、JVM原理解析等...這些成為架構(gòu)師必備的內(nèi)容)以及Java進階學(xué)習(xí)路線圖。
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[] resize() { //引用擴容前的Entry數(shù)組 Node [] oldTab = table; int oldCap = (oldTab == null) ? 0 : oldTab.length; int oldThr = threshold; int newCap, newThr = 0; if (oldCap > 0) { // 擴容前的數(shù)組大小如果已經(jīng)達(dá)到最大(2^30)了 //在這里去判斷是否達(dá)到最大的大小 if (oldCap >= MAXIMUM_CAPACITY) { //修改閾值為int的最大值(2^31-1),這樣以后就不會擴容了 threshold = Integer.MAX_VALUE; return oldTab; } // 如果擴容后小于最大值 而且 舊數(shù)組桶大于初始容量16, 閾值左移1(擴大2倍) else if ((newCap = oldCap << 1) < MAXIMUM_CAPACITY && oldCap >= DEFAULT_INITIAL_CAPACITY) newThr = oldThr << 1; // double threshold } // 如果數(shù)組桶容量<=0 且 舊閾值 >0 else if (oldThr > 0) // initial capacity was placed in threshold //新的容量就等于舊的閥值 newCap = oldThr; else { // zero initial threshold signifies using defaults // 如果數(shù)組桶容量<=0 且 舊閾值 <=0 // 新容量=默認(rèn)容量 // 新閾值= 負(fù)載因子*默認(rèn)容量 newCap = DEFAULT_INITIAL_CAPACITY; newThr = (int)(DEFAULT_LOAD_FACTOR * DEFAULT_INITIAL_CAPACITY); } // 如果新閾值為0 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"}) //創(chuàng)建新的數(shù)組 Node [] newTab = (Node [])new Node[newCap]; // 覆蓋數(shù)組桶 table = newTab; // 如果舊數(shù)組桶不是空,則遍歷桶數(shù)組,并將鍵值對映射到新的桶數(shù)組中 //在這里還有一點詭異的,1.7是不存在后邊紅黑樹的,但是1.8就是有紅黑樹 if (oldTab != null) { for (int j = 0; j < oldCap; ++j) { Node 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 )e).split(this, newTab, j, oldCap); else { // preserve order // 如果不是紅黑樹,那也就是說他鏈表長度沒有超過8,那么還是鏈表, //那么還是會按照鏈表處理 Node loHead = null, loTail = null; Node hiHead = null, hiTail = null; Node next; // 遍歷鏈表,并將鏈表節(jié)點按原順序進行分組 do { next = e.next; if ((e.hash & oldCap) == 0) { if (loTail == null) loHead = e; else loTail.next = e; loTail = e; } 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;}復(fù)制代碼
所以說在經(jīng)過resize這個方法之后,元素的位置要么就是在原來的位置,要么就是在原來的位置移動2次冪的位置上。 源碼上的注釋也是可以翻譯出來的
/** * 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 如果為null,則分配符合字段閾值中保存的初始容量目標(biāo)。 否則,因為我們使用的是2次冪擴展, 所以每個bin中的元素必須保持相同的索引,或者在新表中以2的偏移量移動。 */ final Node[] resize() .....復(fù)制代碼
所以說他的擴容其實很有意思,就有了三種不同的擴容方式了,
在HashMap剛初始化的時候,使用默認(rèn)的構(gòu)造初始化,會返回一個空的table,并且 thershold為0,因此第一次擴容的時候默認(rèn)值就會是16. 同時再去計算thershold = DEFAULT_LOAD_FACTOR * DEFAULT_INITIAL_CAPACITY = 16*0.75 = 12.
如果說指定初始容量的初始HashMap的時候,那么這時候計算這個threshold的時候就變成了 threshold = DEFAULT_LOAD_FACTOR * threshold(當(dāng)前的容量)
到此,關(guān)于“HashMap的底層實現(xiàn)原理”的學(xué)習(xí)就結(jié)束了,希望能夠解決大家的疑惑。理論與實踐的搭配能更好的幫助大家學(xué)習(xí),快去試試吧!若想繼續(xù)學(xué)習(xí)更多相關(guān)知識,請繼續(xù)關(guān)注創(chuàng)新互聯(lián)網(wǎng)站,小編會繼續(xù)努力為大家?guī)砀鄬嵱玫奈恼拢?/p>
當(dāng)前文章:HashMap的底層實現(xiàn)原理
網(wǎng)頁URL:http://weahome.cn/article/gccehp.html