Java詳細分析講解HashMap
java集合容器類分為Collection和Map兩大類,Collection類的子接口有Set、List、Queue,Map類子接口有SortedMap。如ArrayList、HashMap的繼承實現(xiàn)關(guān)系分別如下
1.HashMap數(shù)據(jù)結(jié)構(gòu)
在jdk1.8中,底層數(shù)據(jù)結(jié)構(gòu)是“數(shù)組+鏈表+紅黑樹”。HashMap其實底層實現(xiàn)還是數(shù)組,只是數(shù)組的每一項都是一條鏈,如下
當鏈表過長時,會嚴重影響HashMap的性能,紅黑樹的搜索時間復(fù)雜度是O(logn),而鏈表是O(n),因此在jdk1.8引入了紅黑樹做進一步優(yōu)化,鏈表和紅黑樹在達到一定條件進行轉(zhuǎn)換:
- 當鏈表轉(zhuǎn)換為紅黑樹前會判斷,如果當前數(shù)組的長度小于64,那么會選擇先進行數(shù)組擴容,而不是轉(zhuǎn)換為紅黑樹,以減少搜索時間;
- 當鏈表超過8且數(shù)組長度超過64才會轉(zhuǎn)為紅黑樹;
2.HashMap特點
HashMap存取是無序的;K和V都可以是null,但是K只能由一個null;閾值大于8且數(shù)組長度大于64時才將鏈表轉(zhuǎn)換為紅黑樹,變成紅黑樹的目的是提高搜索速度。
鏈表轉(zhuǎn)換為紅黑樹的原因:在數(shù)組比較小的時候如果出現(xiàn)紅黑樹,反而降低效率,而紅黑樹需要進行左旋右旋、變色操作來保持平衡,同事數(shù)組長度小于64時,搜索速度也較快。
默認加載因子為0.75的原因:HashMap中的threadhold是HashMap所能容納鍵值對的最大值,計算公式為threadhold =leng*loadFactory,在數(shù)組定義好長度之后,負載因子越大,所能容納的鍵值對的個數(shù)越大。loadFactory越趨近于1,那么數(shù)組中存放的數(shù)據(jù)越密集,就會有更多的鏈表長度處于更長的數(shù)值,我們的查詢效率就會越低,當添加數(shù)據(jù)時,產(chǎn)生hash沖突的概率也會越高。loadFactory越趨近于0.數(shù)組中存放的數(shù)據(jù)越稀疏,0.75是對空間和時間效率的一種平衡選擇,經(jīng)過多重計算檢驗得到的可靠值。
hash值計算:hashCode方法是Object中的方法,所有類都可以對其進行使用,首先底層通過調(diào)用hashCode方法生成初始hash值h1,然后將h1無符號右移16位得到h2,之后將h1和h2進行按位異或運算得到最終的hash值h3,之后將h3與length-1進行按位與運算得到hash表索引。
3.HashMap中put方法流程
源碼如下
public V put(K key, V value) { return putVal(hash(key), key, value, false, true); } /** * 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; }
首先根據(jù)key的值計算hash值,找到該元素在數(shù)組中存儲的下標;
若數(shù)組是空的,則調(diào)用resize進行初始化;
若沒有hash沖突,則直接放在對應(yīng)的數(shù)組下標里;
若發(fā)生hash沖突了,且key已經(jīng)存儲,就覆蓋掉value;
若發(fā)生hash沖突后是鏈表結(jié)構(gòu),就判斷該鏈表是否大于8,若大于8且數(shù)組容量小于64,就進行擴容;若鏈表節(jié)點數(shù)量大于8且數(shù)組容量大于64,則將這個結(jié)構(gòu)轉(zhuǎn)換位紅黑樹;否則鏈表插入鍵值對,若key存在則覆蓋掉value;
若hash沖突后,發(fā)現(xiàn)該節(jié)點是紅黑樹,就將這個節(jié)點掛在數(shù)上;
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; } 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; 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 = 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) { 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; }
hashMap在容量超過負載因子后就會擴容,將hashMap的大小擴大為原來數(shù)組的兩倍。
HashMap是非線程安全的,在put的時候,插入的元素超過了容量的范圍就會進行擴容操作rehash,這個會重新將原數(shù)組的內(nèi)容重新hash到新的擴容數(shù)組中,在多線程的環(huán)境下,存在同時其他的元素也在進行put操作,如果hash值相同,可能出現(xiàn)在同一數(shù)組下用鏈表表示,造成閉環(huán),導(dǎo)致在get操作時出現(xiàn)死循環(huán),所以hashMap是線程不安全的。
繼續(xù)理解源碼的設(shè)計妙處。
到此這篇關(guān)于Java詳細分析講解HashMap的文章就介紹到這了,更多相關(guān)Java HashMap內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
springsecurity記住我登錄時訪問無權(quán)限接口跳轉(zhuǎn)登錄界面的處理方案
這篇文章主要介紹了springsecurity記住我登錄時訪問無權(quán)限接口跳轉(zhuǎn)登錄界面的處理方案,本文給大家介紹的非常詳細,對大家的學(xué)習(xí)或工作具有一定的參考借鑒價值,需要的朋友參考下吧2024-02-02java代碼規(guī)范之不合理命名與重復(fù)代碼示例詳解
這篇文章主要為大家介紹了java代碼規(guī)范之不合理命名與重復(fù)代碼示例詳解,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進步,早日升職加薪2023-09-09SpringBoot數(shù)據(jù)庫恢復(fù)的兩種方法mysqldump和mysqlbinlog
binlog用來實現(xiàn)主從復(fù)制,也常用來誤刪數(shù)據(jù)庫找回丟失的記錄,本文主要介紹了SpringBoot數(shù)據(jù)庫恢復(fù)的兩種方法mysqldump和mysqlbinlog,具有一定的參考價值,感興趣的可以了解一下2024-01-01