日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程资源 > 编程问答 >内容正文

编程问答

HashMap jdk1.7和1.8概述

發布時間:2023/12/10 编程问答 25 豆豆
生活随笔 收集整理的這篇文章主要介紹了 HashMap jdk1.7和1.8概述 小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
大家好,我是烤鴨:
這是一篇關于HashMap的概述和底層原理的介紹。算是網上很多帖子的綜合和我自己的一點想法。
HashMap在jdk1.8以前是數組+鏈表。

在jdk1.8以后是數組+鏈表+紅黑樹。一點點分析數據結構。


1.?Map中的entry對象:

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;}}

2.load-factor負載因子和capacity容量

簡單說一下存儲就是node中key計算的hash值決定存儲在數組中的位置的bucket(桶)。

如果hash值一樣,數組中該位置的bucket(桶)里就會變成鏈表。
在jdk1.8,鏈表的長度如果>8,就會變成紅黑樹。

與HashMap實例相關的參數常用的有兩個,load-factor負載因子和capacity容量。
簡單解釋一下兩個參數:
loadFactor 就是創建hashMap什么時間擴容。舉個例子來說:

默認new一個HashMap的capacity:16,loadFactor:0.75。

/*** Constructs an empty <tt>HashMap</tt> with the default initial capacity* (16) and the default load factor (0.75).*/public HashMap() {this.loadFactor = DEFAULT_LOAD_FACTOR; // all other fields defaulted}/*** The load factor used when none specified in constructor.*/static final float DEFAULT_LOAD_FACTOR = 0.75f;16*0.75 = 12;
? ? 也就是當Map的大小達到12的時候,開始擴容。

? ? 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<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 thresholdnewCap = oldThr;else { // zero initial threshold signifies using defaultsnewCap = 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 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;}else {if (hiTail == null)hiHead = e;elsehiTail.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;}

看這句:

else if ((newCap = oldCap << 1) < MAXIMUM_CAPACITY &&oldCap >= DEFAULT_INITIAL_CAPACITY) newThr = oldThr << 1; // double threshold就知道,每次擴容都是之前的2倍。第一次的大小是16,擴容后就變成32。
這里注意一下1.7和1.8的變化;
先說一下1.7的源碼:

轉自:http://blog.csdn.net/yimi099/article/details/62043566

3. 1.7源碼

void resize(int newCapacity) { //傳入新的容量 Entry[] oldTable = table; //引用擴容前的Entry數組 int oldCapacity = oldTable.length; if (oldCapacity == MAXIMUM_CAPACITY) { //擴容前的數組大小如果已經達到最大(2^30)了 threshold = Integer.MAX_VALUE; //修改閾值為int的最大值(2^31-1),這樣以后就不會擴容了 return; } Entry[] newTable = new Entry[newCapacity]; //初始化一個新的Entry數組 transfer(newTable); //!!將數據轉移到新的Entry數組里 table = newTable; //HashMap的table屬性引用新的Entry數組 threshold = (int) (newCapacity * loadFactor);//修改閾值 } void transfer(Entry[] newTable) { Entry[] src = table; //src引用了舊的Entry數組 int newCapacity = newTable.length; for (int j = 0; j < src.length; j++) { //遍歷舊的Entry數組 Entry<K, V> e = src[j]; //取得舊Entry數組的每個元素 if (e != null) { src[j] = null;//釋放舊Entry數組的對象引用(for循環后,舊的Entry數組不再引用任何對象) do { Entry<K, V> next = e.next; int i = indexFor(e.hash, newCapacity); //!!重新計算每個元素在數組中的位置 e.next = newTable[i]; //標記[1] newTable[i] = e; //將元素放在數組上 e = next; //訪問下一個Entry鏈上的元素 } while (e != null); } } }

1.7里是每次擴容都去計算元素的hash值,從而改變該元素在數組中的位置。capacity變了,位置自然就要改變。

1.8做了優化:

do {next = e.next;if ((e.hash & oldCap) == 0) {if (loTail == null)loHead = e;elseloTail.next = e;loTail = e;}else {if (hiTail == null)hiHead = e;elsehiTail.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;}

解釋一下什么意思。

轉自:http://blog.csdn.net/brycegao321/article/details/52527236/

(e.hash & oldCap) == 0寫的很贊!!! 它將原來的鏈表數據散列到2個下標位置,? 概率是當前位置50%,高位位置50%。? ? ?你可能有點懵比, 下面舉例說明。? 上邊圖中第0個下標有496和896,? 假設它倆的hashcode(int型,占4個字節)是

resize前:
496的hashcode: 00000000? 00000000? 00000000? 00000000
896的hashcode: 01010000? 01100000? 10000000? 00100000
oldCap是16:? ? ? ?00000000? 00000000? 00000000? 00010000

496和896對應的e.hash & oldCap的值為0, 即下標都是第0個。

resize后:
496的hashcode: 00000000? 00000000? 00000000? 00000000
896的hashcode: 01010000? 01100000? 10000000? 00100000
oldCap是32:? ? ? ?00000000? 00000000? 00000000? 00100000

496和896對應的e.hash & oldCap的值為0和1, 即下標都是第0個和第16個。

因為hashcode的第n位是0/1的概率相同, 理論上鏈表的數據會均勻分布到當前下標或高位數組對應下標。

再說一下其他參數:
bucket桶:
數組中每一個位置上都放有一個桶,每個桶里就是裝一個鏈表,鏈表中可以有很多個元素(entry),這就是桶的意思。也就相當于把元素都放在桶中。
size:

HashMap的實例中實際存儲的元素的個數。

4.?threshold:

threshold = capacity * loadFactor,當Size>=threshold的時候,那么就要考慮對數組的擴增了,也就是說,這個的意思就是衡量數組是否需要擴增的一個標準。

/*** 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.*/ static final int TREEIFY_THRESHOLD = 8; 對于一個桶(容器)來說,桶的統計臨界值比起list集合更用于樹。
當向有多很節點的桶添加一個元素的時候,桶轉換成樹。這個很多節點就是8。
再說下擴容的過程:

是否擴容主要看:threshold這個參數,threshold = capacity*loadFactor,初始值是threshold = 16*0.75=12,第一次擴容capacity=capacity*2=32,threshold =threshold *2=24。

5. 1.8源碼的put方法

再說一下put方法:

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; //初始化桶,默認16個元素if ((p = tab[i = (n - 1) & hash]) == null) //如果第i個桶為空,創建Node實例tab[i] = newNode(hash, key, value, null);else { //哈希碰撞的情況, 即(n-1)&hash相等Node<K,V> e; K k;if (p.hash == hash &&((k = p.key) == key || (key != null && key.equals(k))))e = p; //key相同,后面會覆蓋valueelse if (p instanceof TreeNode)e = ((TreeNode<K,V>)p).putTreeVal(this, tab, hash, key, value); //紅黑樹添加當前nodeelse {for (int binCount = 0; ; ++binCount) {if ((e = p.next) == null) {p.next = newNode(hash, key, value, null); //鏈表添加當前元素if (binCount >= TREEIFY_THRESHOLD - 1) // -1 for 1sttreeifyBin(tab, hash); //當鏈表個數大于等于7時,將鏈表改造為紅黑樹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; //覆蓋key相同的value并return, 即不會執行++size}}++modCount;if (++size > threshold) //key不相同時,每次插入一條數據自增1. 當size大于threshold時resizeresize();afterNodeInsertion(evict);return null; }提一個新的名詞,哈希碰撞。
如果hashMap的key和key的hashCode找到數組中同一個位置,就是哈希碰撞。

哈希碰撞是產生鏈表的原因。

最后!!!!

1,HashMap的初始容量是16個, 而且容量只能是2的冪。? 每次擴容時都是變成原來的2倍。
2,默認的負載因子是0.75f,threshold:16*0.75=12。即默認的HashMap實例在插入第13個數據時,會擴容為32。
3,JDK1.8對HashMap的優化, 哈希碰撞后的鏈表上達到8個節點時要將鏈表重構為紅黑樹,? 查詢的時間復雜度變為O(logN)。
4,通常hashMap查詢的時間復雜度是O(N),1.8以后紅黑樹的查詢的時間復雜度是O(logN)。極少數情況不會出現哈希碰撞,那是數組,查詢的時間復雜度是O(1)。
5,初始化數組或者擴容為2倍,初值為空時,則根據初始容量開辟空間來創建數組。否則, 因為我們使用2的冪定義數組大小,數據要么待在原來的下標, 或者移動到新數組的高位下標。?

總結

以上是生活随笔為你收集整理的HashMap jdk1.7和1.8概述的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。