一、JDK7及以前java
二、JKD8及以後node
由上面結構圖可知,在JDK7及以前,HashMap採用位桶+鏈表實現,即便用鏈表處理衝突,同一hash值的鏈表都存儲在一個鏈表裏。可是當位於一個桶中的元素較多,即hash值相等的元素較多時,經過key值依次查找的效率較低。而JDK8對HashMap作了優化,採用位桶+鏈表+紅黑樹實現,當鏈表長度超過閾值(8)時,將鏈表轉換爲紅黑樹,使得HashMap存取速度更快。數據庫
不一樣JDK版本中HashMap重要參數對比數組
屬性名 | 屬性說明 | JDK7 | JDK8 |
loadFactor | 加載因子,初始值=0.75,與擴容有關 | √ | √ |
threshold | 臨界值,與HashMap擴容相關 | √ | √ |
modCount | map中數據改變次數的統計 | √ | √ |
DEFAULT_INITIAL_CAPACITY | 默認的初始容量 ,=1<<4=16 | √ | √ |
MAXIMUM_CAPACITY | 最大容量,=1<<30 | √ | √ |
DEFAULT_LOAD_FACTOR | 默認加載因子,=0.75 | √ | √ |
TREEIFY_THRESHOLD | 使用TreeNode的臨界值,默認=8 | × | √ |
UNTREEIFY_THRESHOLD | 與split方法有關 | × | √ |
MIN_TREEIFY_CAPACITY | 最小TreeNode的容量爲64 | × | √ |
JDK8app
public HashMap(int initialCapacity, float loadFactor) { if (initialCapacity < 0) throw new IllegalArgumentException("Illegal initial capacity: " + initialCapacity); if (initialCapacity > MAXIMUM_CAPACITY) initialCapacity = MAXIMUM_CAPACITY; if (loadFactor <= 0 || Float.isNaN(loadFactor)) throw new IllegalArgumentException("Illegal load factor: " + loadFactor); this.loadFactor = loadFactor; this.threshold = tableSizeFor(initialCapacity); } public HashMap(int initialCapacity) { this(initialCapacity, DEFAULT_LOAD_FACTOR); } public HashMap() { this.loadFactor = DEFAULT_LOAD_FACTOR; // all other fields defaulted }
JDK7函數
public HashMap(int initialCapacity, float loadFactor) { if (initialCapacity < 0) throw new IllegalArgumentException("Illegal initial capacity: " + initialCapacity); if (initialCapacity > MAXIMUM_CAPACITY) initialCapacity = MAXIMUM_CAPACITY; if (loadFactor <= 0 || Float.isNaN(loadFactor)) throw new IllegalArgumentException("Illegal load factor: " + loadFactor); this.loadFactor = loadFactor; threshold = initialCapacity; init(); } public HashMap(int initialCapacity) { this(initialCapacity, DEFAULT_LOAD_FACTOR); } public HashMap() { this(DEFAULT_INITIAL_CAPACITY, DEFAULT_LOAD_FACTOR); }
比較發現最大的改變就是在無參構造函數時,JDK8僅僅是初始化loadFactor讓其等於默認值。而JDK7是調用了一個有參的構造函數,參數使用了默認值。源碼分析
Map經過構造函數new一個HashMap時,其內部存儲數據的數組並無實例化,而是在PUT方法中去作了一件判斷table是否爲空的事,若爲空就會調用resize()方法,resize()第一次調用就會實例化一個長度爲DEFAULT_INITIAL_CAPACITY的Node[]。優化
先來看一張流程圖:this
該流程圖闡述了putVal()方法的整個執行過程。如今咱們來看putVal()的源碼:spa
//對外開發使用 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) { //定義一個數組,一個鏈表,n永遠存放數組長度,i用於存放key的hash計算後的值,即key在數組中的索引 Node<K,V>[] tab; Node<K,V> p; int n, i; //判斷table是否爲空或數組長度爲0,若是爲空則經過resize()實例化一個數組並讓tab做爲其引用,而且讓n等於實例化tab後的長度 if ((tab = table) == null || (n = tab.length) == 0) n = (tab = resize()).length; //根據key通過hash()方法獲得的hash值與數組最大索引作與運算獲得當前key所在的索引值,而且將當前索引上的Node賦予給p並判斷是否該Node是否存在 if ((p = tab[i = (n - 1) & hash]) == null) tab[i] = newNode(hash, key, value, null);//若tab[i]不存在,則直接將key-value插入該位置上。 //該位置存在數據的狀況 else { Node<K,V> e; K k; //從新定義一個Node,和一個k // 該位置上數據Key計算後的hash等於要存放的Key計算後的hash而且該位置上的Key等於要存放的Key if (p.hash == hash &&((k = p.key) == key || (key != null && key.equals(k)))) e = p; //true,將該位置的Node賦予給e else if (p instanceof TreeNode) //判斷當前桶類型是不是TreeNode //ture,進行紅黑樹插值法,寫入數據 e = ((TreeNode<K,V>)p).putTreeVal(this, tab, hash, key, value); else { //false, 遍歷當前位置鏈表 for (int binCount = 0; ; ++binCount) { //查找當前位置鏈表上的表尾,表尾的next節點必然爲null,找到表尾將數據賦給下一個節點 if ((e = p.next) == null) { p.next = newNode(hash, key, value, null); //是,直接將數據寫到下個節點 // 若是此時已經到第八個了,還沒找個表尾,那麼從第八個開始就要進行紅黑樹操做 if (binCount >= TREEIFY_THRESHOLD - 1) treeifyBin(tab, hash); //紅黑樹插值具體操做 break; } //若是當前位置的key與要存放的key的相同,直接跳出,不作任何操做 if (e.hash == hash && ((k = e.key) == key || (key != null && key.equals(k)))) break; //將下一個給到p進行逐個查找節點爲空的Node p = e; } } //若是e不爲空,即找到了一個去存儲Key-value的Node if (e != null) { // existing mapping for key V oldValue = e.value; if (!onlyIfAbsent || oldValue == null) e.value = value; afterNodeAccess(e); return oldValue; } } ++modCount; //當最後一次調整以後Size大於了臨界值,須要調整數組的容量 if (++size > threshold) resize(); afterNodeInsertion(evict); return null; }
源碼以下:
//對外公開方法 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; //保證Map中的數組不爲空,而且存儲的有值,而且查找的key對應的索引位置上有值 if ((tab = table) != null && (n = tab.length) > 0 && (first = tab[(n - 1) & hash]) != null) { // always check first node 第一次就找到了對應的值 if (first.hash == hash && ((k = first.key) == key || (key != null && key.equals(k)))) return first; //判斷下一個節點是否存在 if ((e = first.next) != null) { //true,檢測是不是TreeNode if (first instanceof TreeNode) return ((TreeNode<K,V>)first).getTreeNode(hash, key); //經過TreeNode的get方法獲取值 //否,遍歷鏈表 do { //判斷下一個節點是不是要查找的對象 if (e.hash == hash && ((k = e.key) == key || (key != null && key.equals(k)))) return e; }while ((e = e.next) != null); } }//未找到,返回null return null; }
構造hash表時,若是不指明初始大小,默認大小爲16(即Node數組大小16),若是Node[]數組中的元素達到(填充比*Node.length)從新調整HashMap大小變爲原來2倍大小,擴容很耗時。
resize()源碼以下:
final Node<K,V>[] resize() { Node<K,V>[] oldTab = table; int oldCap = (oldTab == null) ? 0 : oldTab.length; //未擴容時數組的容量 int oldThr = threshold; int newCap, newThr = 0;//定義新的容量和臨界值 //當前Map容量大於零,非第一次put值 if (oldCap > 0) { if (oldCap >= MAXIMUM_CAPACITY) { //超過最大容量:2^30 //臨界值等於Integer類型的最大值 0x7fffffff=2^31-1 threshold = Integer.MAX_VALUE; return oldTab; } //當前容量在默認值和最大值的一半之間 else if ((newCap = oldCap << 1) < MAXIMUM_CAPACITY && oldCap >= DEFAULT_INITIAL_CAPACITY) newThr = oldThr << 1; //新臨界值爲當前臨界值的兩倍 } //當前容量爲0,可是當前臨界值不爲0,讓新的容量等於當前臨界值 else if (oldThr > 0) newCap = oldThr; //當前容量和臨界值都爲0,讓新的容量爲默認值,臨界值=初始容量*默認加載因子 else { 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; //擴容table 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;//此時newCap = oldCap*2 else if (e instanceof TreeNode) //節點爲紅黑樹,進行切割操做 ((TreeNode<K,V>)e).split(this, newTab, j, oldCap); else { //鏈表的下一個節點還有值,但節點位置又沒有超過8 //lo就是擴容後仍然在原地的元素鏈表 //hi就是擴容後下標爲 原位置+原容量 的元素鏈表,從而不須要從新計算hash。 Node<K,V> loHead = null, loTail = null; Node<K,V> hiHead = null, hiTail = null; Node<K,V> next; //循環鏈表直到鏈表末再無節點 do { next = e.next; //e.hash&oldCap == 0 判斷元素位置是否還在原位置 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); //循環鏈表結束,經過判斷loTail是否爲空來拷貝整個鏈表到擴容後table if (loTail != null) { loTail.next = null; newTab[j] = loHead; } if (hiTail != null) { hiTail.next = null; newTab[j + oldCap] = hiHead; } } } } } return newTab; }
String類型和Integer類型的hashCode值,Map中hash方法
//String類型 HashCode public int hashCode() { int h = hash; if (h == 0 && value.length > 0) { char val[] = value; for (int i = 0; i < value.length; i++) { h = 31 * h + val[i]; } hash = h; } return h; } //Integer類型的 HashCode ,就是value自己 public static int hashCode(int value) { return value; } //HashMap中的hash(), 小於2^16的值的hashCode都是其自己 static final int hash(Object key) { int h; return (key == null) ? 0 : (h = key.hashCode()) ^ (h >>> 16); }
HashMap put與resize的實例圖
關於紅黑樹,能夠查看《爲何MySQL數據庫要用B+樹存儲索引?》
參考
https://blog.csdn.net/weixin_37356262/article/details/80543218