源自:jdk1.8.0_121 HashMap继承自AbstractMap,实现了Map、Cloneable、Serializable。
HashMap内部是由数组、链表、红黑树实现的
变量
1 // 默认大小 2 static final int DEFAULT_INITIAL_CAPACITY = 1 << 4; 3 4 // 最大容量 5 static final int MAXIMUM_CAPACITY = 1 << 30; 6 7 // 默认负载因子,默认0.75,当数组 8 static final float DEFAULT_LOAD_FACTOR = 0.75f; 9 10 // 链表长度大于8的时候转红黑树 11 static final int TREEIFY_THRESHOLD = 8; 12 13 // 红黑树节点小于6的时候转链表 14 static final int UNTREEIFY_THRESHOLD = 6; 15 16 // 转换为红黑树之前还得判断数组的容量是否大于64 17 static final int MIN_TREEIFY_CAPACITY = 64; 18 19 // 数组 20 transient Node<K,V>[] table; 21 22 transient Set<Map.Entry<K,V>> entrySet; 23 24 // 数组table的大小 25 transient int size; 26 27 // 操作次数 28 transient int modCount; 29 30 /** 31 * The next size value at which to resize (capacity * load factor). 32 * 33 * @serial 34 */ 35 // (The javadoc description is true upon serialization. 36 // Additionally, if the table array has not been allocated, this 37 // field holds the initial array capacity, or zero signifying 38 // DEFAULT_INITIAL_CAPACITY.) 39 // 这个注释很关键,如果table数组还没被分配时,阈值threshold等于数组的数组容量,反之threshold = capacity * load factor 40 int threshold; 41 42 // 负载因子 43 final float loadFactor; 44
构造方法
1 public HashMap(int initialCapacity, float loadFactor) { 2 if (initialCapacity < 0) 3 throw new IllegalArgumentException("Illegal initial capacity: " + 4 initialCapacity); 5 if (initialCapacity > MAXIMUM_CAPACITY) 6 initialCapacity = MAXIMUM_CAPACITY; 7 if (loadFactor <= 0 || Float.isNaN(loadFactor)) 8 throw new IllegalArgumentException("Illegal load factor: " + 9 loadFactor); 10 this.loadFactor = loadFactor; 11 this.threshold = tableSizeFor(initialCapacity); 12 } 13 14 public HashMap(int initialCapacity) { 15 this(initialCapacity, DEFAULT_LOAD_FACTOR); 16 } 17 18 public HashMap() { 19 this.loadFactor = DEFAULT_LOAD_FACTOR; // all other fields defaulted 20 } 21 22 public HashMap(Map<? extends K, ? extends V> m) { 23 this.loadFactor = DEFAULT_LOAD_FACTOR; 24 putMapEntries(m, false); 25 }
put方法
1 public V put(K key, V value) { 2 return putVal(hash(key), key, value, false, true); 3 } 4 5 final V putVal(int hash, K key, V value, boolean onlyIfAbsent, 6 boolean evict) { 7 Node<K,V>[] tab; Node<K,V> p; int n, i; 8 // 如果数组为null或者数组的大小为0时,对数组进行扩容 9 if ((tab = table) == null || (n = tab.length) == 0) 10 n = (tab = resize()).length; 11 // 因为n为2的a次,(2^a - 1) & hash < 2^a,所以不会越界,当tab[i]为空时(索引不冲突),直接插入数组中 12 if ((p = tab[i = (n - 1) & hash]) == null) 13 tab[i] = newNode(hash, key, value, null); 14 // 索引冲突时 15 else { 16 Node<K,V> e; K k; 17 // 第一个元素hash和key都冲突时 18 if (p.hash == hash && 19 ((k = p.key) == key || (key != null && key.equals(k)))) 20 e = p; 21 // 当p为红黑树时 22 else if (p instanceof TreeNode) 23 // Node转型TreeNode* 24 e = ((TreeNode<K,V>)p).putTreeVal(this, tab, hash, key, value); 25 // 当p为链表时 26 else { 27 // 一直循环到链表的最后一个结点 28 for (int binCount = 0; ; ++binCount) { 29 if ((e = p.next) == null) { 30 p.next = newNode(hash, key, value, null); 31 // 当结点数大于等于8 32 if (binCount >= TREEIFY_THRESHOLD - 1) // -1 for 1st 33 // 链表转红黑树 34 treeifyBin(tab, hash); 35 break; 36 } 37 // 当hash和key都冲突时,也就是找到了此结点,用于替换 38 if (e.hash == hash && 39 ((k = e.key) == key || (key != null && key.equals(k)))) 40 break; 41 p = e; 42 } 43 } 44 // hash和key都冲突时,e才会不等于null 45 if (e != null) { // existing mapping for key 46 V oldValue = e.value; 47 // 如果onlyIfAbsent为false就不会替换原有的值 48 if (!onlyIfAbsent || oldValue == null) 49 // 替换原有的值 50 e.value = value; 51 afterNodeAccess(e); 52 // 返回被替换的值 53 return oldValue; 54 } 55 } 56 ++modCount; 57 // 超过最大容量(length * Load factor)时,扩容 58 if (++size > threshold) 59 resize(); 60 afterNodeInsertion(evict); 61 return null; 62 } 63
tableSizeFor方法
1 // 返回一个最接近cap的2^n幂 2 static final int tableSizeFor(int cap) { 3 int n = cap - 1; 4 n |= n >>> 1; 5 n |= n >>> 2; 6 n |= n >>> 4; 7 n |= n >>> 8; 8 n |= n >>> 16; 9 return (n < 0) ? 1 : (n >= MAXIMUM_CAPACITY) ? MAXIMUM_CAPACITY : n + 1; 10 }
get方法
1 // 通过key的和key的hash获取值 2 public V get(Object key) { 3 Node<K,V> e; 4 return (e = getNode(hash(key), key)) == null ? null : e.value; 5 } 6 7 final Node<K,V> getNode(int hash, Object key) { 8 Node<K,V>[] tab; Node<K,V> first, e; int n; K k; 9 // 首先获取这个key所在的哪一个链表或者红黑树 10 if ((tab = table) != null && (n = tab.length) > 0 && 11 (first = tab[(n - 1) & hash]) != null) { 12 // 如果头结点的key和hash都与要查找的相等时,直接返回头结点 13 if (first.hash == hash && // always check first node 14 ((k = first.key) == key || (key != null && key.equals(k)))) 15 return first; 16 // 头结点的下一个结点不为空时 17 if ((e = first.next) != null) { 18 // 红黑树结点,就查找红黑树 19 if (first instanceof TreeNode) 20 return ((TreeNode<K,V>)first).getTreeNode(hash, key); 21 // 链表,就一直循环到匹配到的key,否则返回null 22 do { 23 if (e.hash == hash && 24 ((k = e.key) == key || (key != null && key.equals(k)))) 25 return e; 26 } while ((e = e.next) != null); 27 } 28 } 29 return null; 30 }
treeifyBin方法
1 // 将Node结点转换成TreeNode结点(其实也就是TreeNode结点的双向链表) 2 final void treeifyBin(Node<K,V>[] tab, int hash) { 3 int n, index; Node<K,V> e; 4 // 数组为空或者数组的大小小于64,扩容 5 if (tab == null || (n = tab.length) < MIN_TREEIFY_CAPACITY) 6 resize(); 7 // 第一个结点不为空时 8 else if ((e = tab[index = (n - 1) & hash]) != null) { 9 // hd 头结点,tl 尾结点 10 TreeNode<K,V> hd = null, tl = null; 11 do { 12 // 将Node结点转换成TreeNode结点 13 TreeNode<K,V> p = replacementTreeNode(e, null); 14 if (tl == null) 15 hd = p; 16 else { 17 p.prev = tl; 18 tl.next = p; 19 } 20 tl = p; 21 } while ((e = e.next) != null); 22 if ((tab[index] = hd) != null) 23 // 将红黑树结点树形化 24 hd.treeify(tab); 25 } 26 }
内部类
HashMap$TreeNode类(红黑树结点)
红黑树的特性
- 每个结点是红色或者黑色。
- 根结点是黑色。
- 每个叶子节点(NIL)是黑色。
- 如果一个节点是红色的,则它的子节点必须是黑色的。
- 从一个节点到该节点的子孙节点的所有路径上包含相同数目的黑节点。
treeify方法
将红黑树结点树形化,变成红黑树的结构。【暂未深入了解】
1 final void treeify(Node<K,V>[] tab) { 2 TreeNode<K,V> root = null; 3 for (TreeNode<K,V> x = this, next; x != null; x = next) { 4 next = (TreeNode<K,V>)x.next; 5 x.left = x.right = null; 6 // 确认根结点,黑色 7 if (root == null) { 8 x.parent = null; 9 x.red = false; 10 root = x; 11 } 12 else { 13 K k = x.key; 14 int h = x.hash; 15 Class<?> kc = null; 16 for (TreeNode<K,V> p = root;;) { 17 int dir, ph; 18 K pk = p.key; 19 // 根结点(p)的hash > 要插入结点(x)的hash时 20 // 插入到根结点的左边 21 if ((ph = p.hash) > h) 22 dir = -1; 23 // 插入到根结点的右边 24 else if (ph < h) 25 dir = 1; 26 else if ((kc == null && 27 (kc = comparableClassFor(k)) == null) || 28 (dir = compareComparables(kc, k, pk)) == 0) 29 dir = tieBreakOrder(k, pk); 30 31 TreeNode<K,V> xp = p; 32 if ((p = (dir <= 0) ? p.left : p.right) == null) { 33 x.parent = xp; 34 if (dir <= 0) 35 xp.left = x; 36 else 37 xp.right = x; 38 root = balanceInsertion(root, x); 39 break; 40 } 41 } 42 } 43 } 44 moveRootToFront(tab, root); 45 }
getTreeNode方法
1 final TreeNode<K,V> getTreeNode(int h, Object k) { 2 return ((parent != null) ? root() : this).find(h, k, null); 3 } 4 5 final TreeNode<K,V> find(int h, Object k, Class<?> kc) { 6 TreeNode<K,V> p = this; 7 do { 8 int ph, dir; K pk; 9 TreeNode<K,V> pl = p.left, pr = p.right, q; 10 if ((ph = p.hash) > h) 11 p = pl; 12 else if (ph < h) 13 p = pr; 14 else if ((pk = p.key) == k || (k != null && k.equals(pk))) 15 return p; 16 else if (pl == null) 17 p = pr; 18 else if (pr == null) 19 p = pl; 20 else if ((kc != null || 21 (kc = comparableClassFor(k)) != null) && 22 (dir = compareComparables(kc, k, pk)) != 0) 23 p = (dir < 0) ? pl : pr; 24 else if ((q = pr.find(h, k, kc)) != null) 25 return q; 26 else 27 p = pl; 28 } while (p != null); 29 return null; 30 }
疑问?
hash % 2^n == hash & (2^n-1)
hash % 2^n 余数是0~2^n-1
hash & (2^n-1) ,也就是取hash的后n位,后n位最大值是2^n-1
当hash = n时
hash
n
hash % 2^n
hash & (2^n-1)
0
0
0
0
1
1
1
1
...
...
...
...
n
n
n
n
当hash = n-a时(hash < n)
hash
n
hash % 2^n
hash & (2^n-1)
0
a
0
0
1
a+1
1
1
...
...
...
...
n-a
n
n-a
n-a
当hash = n+a时(hash > n)
hash
n
hash % 2^n
hash & (2^n-1)
0
-a
0
0
1
-a+1
1
1
...
...
...
...
n+a
n
n+a
n+a
综上所述hash % 2^n == hash & (2^n-1)成立。
Node转型TreeNode(向下转型)
Node跟TreeNode都是HashMap的内部类,怎么还能转型的呢?
1 // 在HashMap里内部类TreeNode继承了LinkedHashMap的内部类Entry 2 static final class TreeNode<K,V> extends LinkedHashMap.Entry<K,V> 3 4 5 // 在LinkedHashMap里内部类Entry又继承了HashMap的内部类Node 6 static class Entry<K,V> extends HashMap.Node<K,V>