HashMap
HashMap源码分析
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 * 2、4、8、16、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); } } }