HashMap源碼分析java
package java.util; import java.io.*; public class HashMap<K,V> extends AbstractMap<K,V> implements Map<K,V>, Cloneable, Serializable { // 默認容量16 static final int DEFAULT_INITIAL_CAPACITY = 1 << 4; // 最大容量,/mæksɪməm/ 最大值的,是Integer最大值2147483647的一半1073741824 static final int MAXIMUM_CAPACITY = 1 << 30; // 負載因子,/ˈfæktə/ 因素、因子 static final float DEFAULT_LOAD_FACTOR = 0.75f; // simple–simplify 簡化 ,beautiful-beautify 美化,ugly-uglify 醜化 // treeifys樹化 threshold /ˈθreʃhəʊld/ 門檻,閾值,臨界值 static final int TREEIFY_THRESHOLD = 8; static final int UNTREEIFY_THRESHOLD = 6; static final int MIN_TREEIFY_CAPACITY = 64; // 存入元素個數 transient int size; transient Node<K,V>[] table; static class Node<K,V> implements Map.Entry<K,V> { final int hash; final K key; V value; Node<K,V> next; ... } /* /ˈθreʃhəʊld/ 閾(yù)值,容量大小*0.75 * new一個HashMap完成時, * HashMap構造方法傳入的容量大小先由threshold先臨時緩存起來, * HashMap內部的數組仍是null * * 第一次put元素時 * 會把這個閾值真正賦值給數組大小 */ int threshold; // 負載因子,若是不指定,會把默認的DEFAULT_LOAD_FACTOR——0.75賦值給它 final float loadFactor; transient int modCount; static final int ALTERNATIVE_HASHING_THRESHOLD_DEFAULT = Integer.MAX_VALUE; // 無參構造方法,調用本類的兩個參數的構造方法 public HashMap() { // DEFAULT_INITIAL_CAPACITY,默認的初始化容量,16 // DEFAULT_LOAD_FACTOR,默認的負載因子0.75 this(DEFAULT_INITIAL_CAPACITY, DEFAULT_LOAD_FACTOR); } // 一個參數的構造方法,傳入參數初始化容量 public HashMap(int initialCapacity) { this(initialCapacity, DEFAULT_LOAD_FACTOR); } // 也能夠指定負載因子 public HashMap(int initialCapacity, float loadFactor) { if (initialCapacity < 0) throw new IllegalArgumentException("Illegal initial capacity: " + initialCapacity); // HashMap的最大容量是Interger最大值的一半 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); } /* HashMap初始化時數組容量由tableSizeFor()方法肯定 * tableSizeFor()方法返回的結果是2的冪 * 傳入1,返回1;傳入2,返回4;傳入7,返回8;傳入13,返回16 * 二、四、八、1六、32減1每一個位置都是1,如16-1=15,1111 * 計算數組下標,i = (n - 1) & hash —— &都爲1結果爲1 * i是下標,n是數組容量,hash是hash值 * 這樣在進行按位與的時候,11...11,能夠使每一位都真正有效 */ 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; } public V put(K key, V value) { return putVal(hash(key), key, value, false, true); } static final int hash(Object key) { int h; // 異或,不一樣爲1,相同爲0 return (key == null) ? 0 : (h = key.hashCode()) ^ (h >>> 16); } 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; /* * 計算下標 * i = (n - 1) & hash, &都爲1結果爲1 * 若是這個下標的數組元素是null,以前沒有插入過,直接插入 */ if ((p = tab[i = (n - 1) & hash]) == null) tab[i] = newNode(hash, key, value, null); // 衝突了 else { Node<K,V> e; K k; // 相同的 key 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); // 若是鏈表元素大於等於8個,把數據放入一個紅黑樹 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) // 若是是key相同,會把新的value覆蓋舊的value e.value = value; afterNodeAccess(e); // 並返回舊的value return oldValue; } } ++modCount; if (++size > threshold) resize(); afterNodeInsertion(evict); return null; } final Node<K,V>[] resize() { // 第一次put元素時,table爲null Node<K,V>[] oldTab = table; // 第一次put元素時,舊數組容量oldCab爲0 int oldCap = (oldTab == null) ? 0 : oldTab.length; int oldThr = threshold; int newCap, newThr = 0; if (oldCap > 0) { // 擴容 if (oldCap >= MAXIMUM_CAPACITY) { // 原數組長度大於最大容量(1073741824) 則將threshold設爲Integer.MAX_VALUE=2147483647 // 接近MAXIMUM_CAPACITY的兩倍 threshold = Integer.MAX_VALUE; return oldTab; } /* 數組容量擴展至原來的兩倍 * 閾值也擴展至原來的兩倍 * 16 12 —— 0.75 * 32 24 —— 0.75 * 64 48 —— 0.75 * 128 96 —— 0.75 */ 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 /* 第一次put元素時, * 把構造HashMap時由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) { /* 第一次put元素時, * 計算新數組閾值 */ float ft = (float)newCap * loadFactor; newThr = (newCap < MAXIMUM_CAPACITY && ft < (float)MAXIMUM_CAPACITY ? (int)ft : Integer.MAX_VALUE); } /* 第一次put元素時, * 爲閾值賦值 */ 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; } final Node<K,V> getNode(int hash, Object key) { Node<K,V>[] tab; Node<K,V> first, e; int n; K k; if ((tab = table) != null && (n = tab.length) > 0 && (first = tab[(n - 1) & hash]) != null) { // 比較hash,且比較key,若是相同,就返回 if (first.hash == hash && // always check first node ((k = first.key) == key || (key != null && key.equals(k)))) return first; if ((e = first.next) != null) { // 判斷是否是紅黑樹 if (first instanceof TreeNode) return ((TreeNode<K,V>)first).getTreeNode(hash, key); do { if (e.hash == hash && ((k = e.key) == key || (key != null && key.equals(k)))) return e; } while ((e = e.next) != null); } } return null; } final void treeifyBin(Node<K,V>[] tab, int hash) { int n, index; Node<K,V> e; if (tab == null || (n = tab.length) < MIN_TREEIFY_CAPACITY) resize(); else if ((e = tab[index = (n - 1) & hash]) != null) { TreeNode<K,V> hd = null, tl = null; do { TreeNode<K,V> p = replacementTreeNode(e, null); if (tl == null) hd = p; else { p.prev = tl; tl.next = p; } tl = p; } while ((e = e.next) != null); if ((tab[index] = hd) != null) hd.treeify(tab); } } static final class TreeNode<K,V> extends LinkedHashMap.Entry<K,V> { TreeNode<K,V> parent; // red-black tree links TreeNode<K,V> left; TreeNode<K,V> right; TreeNode<K,V> prev; // needed to unlink next upon deletion // 紅黑樹 boolean red; TreeNode(int hash, K key, V val, Node<K,V> next) { super(hash, key, val, next); } } }