Java中的HashMap源碼詳解
HashMap
當我們確切知道HashMap將要處理的數(shù)據(jù)量為n時,推薦調(diào)用構(gòu)造函數(shù)public HashMap(int initialCapacity)來創(chuàng)建 HashMap,這樣就不會發(fā)生擴容。
以上構(gòu)造函數(shù)并沒有直接將table數(shù)組的大小設(shè)置為給定的initialCapacity參數(shù)的值n,但是會設(shè)定閾值threshold為大于用戶給定的n的2的乘方的最小值(例如,假如參數(shù)initialCapacity的值是13-16中的任意一個值,threshold都會是16)。
而擴容的條件會分兩種情況:
- 當我們調(diào)用了如上構(gòu)造函數(shù)時,擴容只在size()>=threshold時發(fā)生,只要我們確認實際的數(shù)據(jù)量不會大于在構(gòu)造函數(shù)中傳給參數(shù)initialCapacity的值,那么擴容就不會發(fā)生。
- 如果我們調(diào)用的是無參構(gòu)造函數(shù),那么擴容會發(fā)生在size()>capacity*loadRefactor時。
Map接口
keySet | values | size | containsKey | put | remove |
entrySet | isEmpty | containsValue | get | clear |
以下為部分JDK1.8添加的默認方法,default
getOrdefault(Object o,V v) | replaceAll(BiFunction<K,V,V> f) | remvoe(K k,V v) |
forEach(BiConsumer<K,V> c) | putIfAbsent(K k,V v) | replace |
Map.Entry接口
此接口是定義在Map接口內(nèi)部的static的接口
getKey | setValue | comparingByKey | comparingByKey(Comparator c) |
getValue | equals | comparingByValue | comparingByValue(Comparator c) |
源碼解析
public class HashMap<K,V> extends AbstractMap<K,V> implements Map<K,V>, Cloneable, Serializable {
定義一些默認值
// table的初始大小默認值,即桶個數(shù),必須是2的乘方 static final int DEFAULT_INITIAL_CAPACITY = 1 << 4; // aka 16 // table的大小的最大值,即桶數(shù)的最大值 static final int MAXIMUM_CAPACITY = 1 << 30; // 負載因子,建議0.5-1.5 static final float DEFAULT_LOAD_FACTOR = 0.75f; // 當某個桶內(nèi)元素個數(shù)大于等于此數(shù),并且桶數(shù)大于64時,會將桶內(nèi)元素的存儲結(jié)構(gòu)由單鏈表改為紅黑樹 static final int TREEIFY_THRESHOLD = 8; // 當桶內(nèi)元素個數(shù)小于或者等于此數(shù)時,會將桶內(nèi)元素的存儲結(jié)構(gòu)由紅黑樹改為單鏈表 static final int UNTREEIFY_THRESHOLD = 6; // 若table的大小小于MIN_TREEIFY_CAPACITY 時,即便某個桶內(nèi)的元素個數(shù)達到了TREEIFY_THRESHOLD 后,也并不會對這個桶做樹化操作,而是對map進行擴容resize() static final int MIN_TREEIFY_CAPACITY = 64;
定義內(nèi)部類:封裝鏈表的節(jié)點
static class Node<K,V> implements Map.Entry<K,V> { final int hash; final K key; V value; Node<K,V> next; Node(int hash, K key, V value, Node<K,V> 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; } }
定義實例域
注意:
- 并沒有定義一個capacity實例域來指明table數(shù)組的大小,盡管類中定義了一個靜態(tài)常量DEFAULT_INITIAL_CAPACITY。
- table數(shù)組的大小是在初始化時確定的:參看resize()方法。
- 所有實例域的訪問控制都是默認的
/* ---------------- Fields -------------- */ // 裝桶的數(shù)組,存儲每個桶內(nèi)的單鏈表的頭結(jié)點或者樹的根節(jié)點 transient Node<K,V>[] table; transient Set<Map.Entry<K,V>> entrySet; // Map中當前實際存儲的元素個數(shù) transient int size; // 每次remove,add等都會++modCount,當并發(fā)時,發(fā)現(xiàn)自己的modCount不是原來的了,就會拋出異常,表示并行修改失敗 transient int modCount; // 閾值:當map中的元素個數(shù)大于等于threshold時,會觸發(fā)resize()操作進行擴容。 int threshold; // 負載因子:當用戶調(diào)用的默認無參構(gòu)造函數(shù)、或者map自動擴容時,新的threshold=新table的capacity*loadFactor; final float loadFactor;
定義構(gòu)造函數(shù)
注意:
如果用戶確切知道將要處理的數(shù)據(jù)量為capacity,則可以調(diào)用構(gòu)造函數(shù)public HashMap(int initialCapacity) ,此構(gòu)造函數(shù)會設(shè)定閾值threshold為大于用戶給定的capacity的2的乘方的最小值。
因此用戶在主動設(shè)定capacity后不必擔心自動擴容問題,因為擴容只會在實際數(shù)據(jù)量>=threshold時發(fā)生,而此種情況下threshold>=用戶設(shè)定的capacity會一定成立。 參見:tableSizeFor()方法
/* --------------------------構(gòu)造函數(shù),不會初始化table數(shù)組,table數(shù)組只有在首次調(diào)用put方法時才會被初始化------ */ // 默認構(gòu)造函數(shù),只設(shè)置了負載因子的默認值 public HashMap() { this.loadFactor = DEFAULT_LOAD_FACTOR; // all other fields defaulted } public HashMap(int initialCapacity) { this(initialCapacity, DEFAULT_LOAD_FACTOR); } // 初始化loadFactor 、threshold 的值 // threshold = 大于initialCapacity的最小的2乘方(如,15 ->16 ,13->16) public HashMap(int initialCapacity, float loadFactor) { ... this.loadFactor = loadFactor; this.threshold = tableSizeFor(initialCapacity); } // 計算出大于cap的最小的2的乘方 static final int tableSizeFor(int cap) { int n = cap - 1; n |= n >>> 1; // 00001 0010 | 0000 1001 -> 11011 n |= n >>> 2; // 0001 1011 | 0000 0110 -> 11111 n |= n >>> 4; // 0001 1111 | 0000 0001 -> 11111 n |= n >>> 8; // n |= n >>> 16; return (n < 0) ? 1 : (n >= MAXIMUM_CAPACITY) ? MAXIMUM_CAPACITY : n + 1; }
put方法
- 如果table還未被初始化,則調(diào)用resize()進行初始化
- 如果散列到桶中之后,桶內(nèi)元素個數(shù)>=TREEIFY_THRESHOLD ,則調(diào)用treeifyBin()方法檢查是否要將桶改為紅黑樹結(jié)構(gòu)
- 如果散列到Map中之后,Map中元素個數(shù)>=threshold了,則調(diào)用resize()方法進行擴容
/* ------------------------------put方法------------------------------------------ */ public V put(K key, V value) { return 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; // 頭結(jié)點 int n, i; // n:table的大小。i:新節(jié)點的桶號 // 如果還未被初始化過,則調(diào)用resize(); HashMap在首次調(diào)用put方法之前,是不會初始化table的,因為那樣的話會浪費一塊連續(xù)內(nèi)存。 if ((tab = table) == null || (n = tab.length) == 0) n = (tab = resize()).length; // 根據(jù)key的哈希值,確定桶號,如果桶中還沒有元素,則直接將其作為頭結(jié)點存儲到桶中 if ((p = tab[i = (n - 1) & hash]) == null) tab[i] = newNode(hash, key, value, null); // 獲取到了頭結(jié)點 else { Node<K,V> e; // 目標節(jié)點) K k; // 如果頭結(jié)點的key和新節(jié)點的key相同,則頭結(jié)點即為要被取代的目標節(jié)點 if (p.hash == hash && ((k = p.key) == key || (key != null && key.equals(k)))) e = p; // 如果頭結(jié)點是TreeNode類型的,則調(diào)用putTreeVal方法將新節(jié)點插入,并返回插入后的目標節(jié)點 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) { // 如果沒有找到key相同的節(jié)點,就直接追加到鏈表尾部 p.next = newNode(hash, key, value, null); // 如果桶中元素數(shù)是達到了設(shè)定的變樹閾值(默認值8),則需要將桶內(nèi)元素的存儲結(jié)構(gòu)更新為紅黑樹 if (binCount >= TREEIFY_THRESHOLD - 1) // -1 for 1st treeifyBin(tab, hash); break; } // 如果鏈表中有和新節(jié)點的key相同的元素 if (e.hash == hash && ((k = e.key) == key || (key != null && key.equals(k)))) break; p = e; } } // map中有與新節(jié)點的key相同的元素,那么根據(jù)條件做一些操作,就返回 if (e != null) { // existing mapping for key V oldValue = e.value; // onlyIfAbsent 是方法參數(shù),表示只有不存在相同key的節(jié)點時,才進行更新操作,如果有相同節(jié)點,則不做任何操作。 if (!onlyIfAbsent || oldValue == null) e.value = value; afterNodeAccess(e); //此處是留給LinkedHashMap用的。 return oldValue; } } // else結(jié)束 // 更新了hashMap,就執(zhí)行++modCount; ++modCount; // 當map中的元素數(shù)量大于閾值,就要擴容再散列 if (++size > threshold) resize(); afterNodeInsertion(evict); return null; }
對table數(shù)組初始化 \ 擴容
resize()方法內(nèi)有兩種邏輯:
- 一種是當前table為null時,會對table進行初始化操作;
- 一種是當前table非null,會對table進行擴容操作;
final Node<K,V>[] resize() { // 當前table Node<K,V>[] oldTab = table; // 當前table的大小 int oldCap = (oldTab == null) ? 0 : oldTab.length; // 當前的閾值 int oldThr = threshold; int newCap, newThr = 0; // oldCap>0,說明是要做擴容操作 if (oldCap > 0) { // 如果原本的table的大小已經(jīng)是最大值,無法繼續(xù)擴容,直接退出 if (oldCap >= MAXIMUM_CAPACITY) { threshold = Integer.MAX_VALUE; return oldTab; } // 擴容:設(shè)置新的table的大小為原來的2倍,新的threshold也為原來的2背 else if ((newCap = oldCap << 1) < MAXIMUM_CAPACITY && oldCap >= DEFAULT_INITIAL_CAPACITY) newThr = oldThr << 1; // double threshold } // oldCap<= 0,說明table還未被初始化過,要進行初始化table的操作;oldThr>0,說明用戶調(diào)用的有參構(gòu)造函數(shù),設(shè)置了threshold;直接將根據(jù)用戶參數(shù)計算出的閾值設(shè)定為table的大小 else if (oldThr > 0) // initial capacity was placed in threshold newCap = oldThr; // oldCap<= 0,說明是要進行初始化table的操作;oldThr<0,說明用戶調(diào)用的默認無參構(gòu)造函數(shù);則將各個域變量的值設(shè)置為默認值。 else { // zero initial threshold signifies using defaults newCap = DEFAULT_INITIAL_CAPACITY; newThr = (int)(DEFAULT_LOAD_FACTOR * DEFAULT_INITIAL_CAPACITY); } // 如果經(jīng)過以上設(shè)置,newThr 仍為0,(什么情況下會出現(xiàn)?) if (newThr == 0) { float ft = (float)newCap * loadFactor; newThr = (newCap < MAXIMUM_CAPACITY && ft < (float)MAXIMUM_CAPACITY ? (int)ft : Integer.MAX_VALUE); } threshold = newThr; // 無論是要初始化table,還是要對table進行擴容,經(jīng)過以上邏輯,都已經(jīng)確定了要新創(chuàng)建的table的大小、threshold 。 @SuppressWarnings({"rawtypes","unchecked"}) Node<K,V>[] newTab = (Node<K,V>[])new Node[newCap]; table = newTab; // 如果當前table不為null,說明需要進行擴容操作 if (oldTab != null) { 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 order Node<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; 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; }
到此這篇關(guān)于Java中的HashMap源碼詳解的文章就介紹到這了,更多相關(guān)HashMap源碼內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
Kotlin?標準函數(shù)和靜態(tài)方法示例詳解
這篇文章主要為大家介紹了Kotlin?標準函數(shù)和靜態(tài)方法示例詳解,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進步,早日升職加薪2022-10-10Spring中的@PostConstruct注解使用方法解析
這篇文章主要介紹了Spring中的@PostConstruct注解使用方法解析,@PostConstruct注解是用來處理在@Autowired注入屬性后init()方法之前,對一些零散的屬性進行賦值的注解,需要的朋友可以參考下2023-11-11Java嵌入式開發(fā)的優(yōu)勢及有點總結(jié)
在本篇內(nèi)容里小編給大家整理了關(guān)于Java嵌入式開發(fā)的優(yōu)勢及相關(guān)知識點內(nèi)容,有興趣的朋友們學習下。2022-11-11