作为工作中最重要、最常用的容器之一,当然还是要自己动手写一篇 HashMap 的源码解析来加深对其的印象咯,而且它的设计与实现 也有很多值得学习的地方。

源码赏析

JDK1.8 的 HashMap 底层使用的是 动态数组,数组中元素存放的是 链表或红黑树。核心源码如下。

  1. public class HashMap<K,V> extends AbstractMap<K,V> implements Map<K,V>,
  2. Cloneable, Serializable {
  3. /**
  4. * 初始化容量,这里的 位运算 就不多解释咯,可以自行度娘
  5. */
  6. static final int DEFAULT_INITIAL_CAPACITY = 1 << 4; // aka 16
  7. /**
  8. * 最大容量
  9. */
  10. static final int MAXIMUM_CAPACITY = 1 << 30;
  11. /**
  12. * 扩容因子,使用的容量达到 当前容量的 75% 就扩容
  13. */
  14. static final float DEFAULT_LOAD_FACTOR = 0.75f;
  15. /**
  16. * 当前 HashMap 所能容纳键值对数量的最大值,超过这个值,则需扩容
  17. */
  18. int threshold;
  19. /**
  20. * 已使用的容量
  21. */
  22. transient int size;
  23. /**
  24. * Node数组,实际存放 键值对 的地方
  25. */
  26. transient Node<K,V>[] table;
  27. /**
  28. * 链表转红黑树的阈值,链表长度达到此值,会进化成红黑树
  29. */
  30. static final int TREEIFY_THRESHOLD = 8;
  31. /**
  32. * 系列构造方法,推荐在初始化时根据实际情况设置好初始容量,用好了可以显著减少 resize,提升效率
  33. */
  34. public HashMap(int initialCapacity, float loadFactor) {
  35. if (initialCapacity < 0)
  36. throw new IllegalArgumentException("Illegal initial capacity: " +
  37. initialCapacity);
  38. if (initialCapacity > MAXIMUM_CAPACITY)
  39. initialCapacity = MAXIMUM_CAPACITY;
  40. if (loadFactor <= 0 || Float.isNaN(loadFactor))
  41. throw new IllegalArgumentException("Illegal load factor: " +
  42. loadFactor);
  43. this.loadFactor = loadFactor;
  44. this.threshold = tableSizeFor(initialCapacity);
  45. }
  46. public HashMap(int initialCapacity) {
  47. this(initialCapacity, DEFAULT_LOAD_FACTOR);
  48. }
  49. public HashMap() {
  50. this.loadFactor = DEFAULT_LOAD_FACTOR; // all other fields defaulted
  51. }
  52. public HashMap(Map<? extends K, ? extends V> m) {
  53. this.loadFactor = DEFAULT_LOAD_FACTOR;
  54. putMapEntries(m, false);
  55. }
  56. public V put(K key, V value) {
  57. return putVal(hash(key), key, value, false, true);
  58. }
  59. final V putVal(int hash, K key, V value, boolean onlyIfAbsent,
  60. boolean evict) {
  61. Node<K,V>[] tab; Node<K,V> p; int n, i;
  62. // 初始化桶数组 table,table 被延迟到插入新数据时再进行初始化
  63. if ((tab = table) == null || (n = tab.length) == 0)
  64. n = (tab = resize()).length;
  65. // 如果桶中不包含键值对节点引用,则将新键值对节点的引用存入桶中即可
  66. if ((p = tab[i = (n - 1) & hash]) == null)
  67. tab[i] = newNode(hash, key, value, null);
  68. else {
  69. Node<K,V> e; K k;
  70. // 如果键的值以及节点 hash 等于链表中的第一个键值对节点时,则将 e 指向该键值对
  71. if (p.hash == hash && ((k = p.key) == key || (key != null && key.equals(k))))
  72. e = p;
  73. // 如果桶中的引用类型为 TreeNode,则调用红黑树的插入方法
  74. else if (p instanceof TreeNode)
  75. e = ((TreeNode<K,V>)p).putTreeVal(this, tab, hash, key, value);
  76. else {
  77. // 对链表进行遍历,并统计链表长度
  78. for (int binCount = 0; ; ++binCount) {
  79. // 链表中不包含要插入的键值对节点时,则将该节点接在链表的最后
  80. // !!! JDK1.7中 新增的Node节点采用头插入,而JDK1.8中改成了尾插入 !!!
  81. if ((e = p.next) == null) {
  82. p.next = newNode(hash, key, value, null);
  83. // 如果链表长度达到阈值,则进化成红黑树
  84. if (binCount >= TREEIFY_THRESHOLD - 1) // -1 for 1st
  85. treeifyBin(tab, hash);
  86. break;
  87. }
  88. // 条件为 true,表示当前链表包含要插入的键值对,终止遍历
  89. if (e.hash == hash &&
  90. ((k = e.key) == key || (key != null && key.equals(k))))
  91. break;
  92. p = e;
  93. }
  94. }
  95. // 判断要插入的键值对是否存在 HashMap 中
  96. if (e != null) { // existing mapping for key
  97. V oldValue = e.value;
  98. // onlyIfAbsent 表示是否仅在 oldValue 为 null 的情况下更新键值对的值
  99. if (!onlyIfAbsent || oldValue == null)
  100. e.value = value;
  101. afterNodeAccess(e);
  102. return oldValue;
  103. }
  104. }
  105. ++modCount;
  106. // 键值对数量超过阈值时,则进行扩容
  107. if (++size > threshold)
  108. resize();
  109. afterNodeInsertion(evict);
  110. return null;
  111. }
  112. /**
  113. * 扩容为原容量的两倍,并将存在的元素 放到新的数组上
  114. */
  115. final Node<K,V>[] resize() {
  116. Node<K,V>[] oldTab = table;
  117. int oldCap = (oldTab == null) ? 0 : oldTab.length;
  118. int oldThr = threshold;
  119. int newCap, newThr = 0;
  120. // 如果 table 不为空,表明已经初始化过了
  121. if (oldCap > 0) {
  122. // 当 table 容量超过容量最大值,则不再扩容
  123. if (oldCap >= MAXIMUM_CAPACITY) {
  124. threshold = Integer.MAX_VALUE;
  125. return oldTab;
  126. }
  127. // 按旧容量和阈值的2倍计算新容量和阈值的大小
  128. else if ((newCap = oldCap << 1) < MAXIMUM_CAPACITY &&
  129. oldCap >= DEFAULT_INITIAL_CAPACITY)
  130. newThr = oldThr << 1; // double threshold
  131. } else if (oldThr > 0) // initial capacity was placed in threshold
  132. // 初始化时,将 threshold 的值赋值给 newCap,
  133. // HashMap 使用 threshold 变量暂时保存 initialCapacity 参数的值
  134. newCap = oldThr;
  135. else { // zero initial threshold signifies using defaults
  136. // 调用无参构造方法时,桶数组容量为默认容量,
  137. // 阈值为默认容量与默认负载因子乘积
  138. newCap = DEFAULT_INITIAL_CAPACITY;
  139. newThr = (int)(DEFAULT_LOAD_FACTOR * DEFAULT_INITIAL_CAPACITY);
  140. }
  141. // newThr 为 0 时,按阈值计算公式进行计算
  142. if (newThr == 0) {
  143. float ft = (float)newCap * loadFactor;
  144. newThr = (newCap < MAXIMUM_CAPACITY && ft < (float)MAXIMUM_CAPACITY ?
  145. (int)ft : Integer.MAX_VALUE);
  146. }
  147. threshold = newThr;
  148. // 创建新的桶数组,桶数组的初始化也是在这里完成的
  149. Node<K,V>[] newTab = (Node<K,V>[])new Node[newCap];
  150. table = newTab;
  151. if (oldTab != null) {
  152. // 如果旧的桶数组不为空,则遍历桶数组,并将键值对映射到新的桶数组中
  153. for (int j = 0; j < oldCap; ++j) {
  154. Node<K,V> e;
  155. if ((e = oldTab[j]) != null) {
  156. oldTab[j] = null;
  157. if (e.next == null)
  158. newTab[e.hash & (newCap - 1)] = e;
  159. else if (e instanceof TreeNode)
  160. // 重新映射时,需要对红黑树进行拆分
  161. ((TreeNode<K,V>)e).split(this, newTab, j, oldCap);
  162. else { // preserve order
  163. Node<K,V> loHead = null, loTail = null;
  164. Node<K,V> hiHead = null, hiTail = null;
  165. Node<K,V> next;
  166. // 遍历链表,并将链表节点按原顺序进行分组
  167. do {
  168. next = e.next;
  169. if ((e.hash & oldCap) == 0) {
  170. if (loTail == null)
  171. loHead = e;
  172. else
  173. loTail.next = e;
  174. loTail = e;
  175. }
  176. else {
  177. if (hiTail == null)
  178. hiHead = e;
  179. else
  180. hiTail.next = e;
  181. hiTail = e;
  182. }
  183. } while ((e = next) != null);
  184. // 将分组后的链表映射到新桶中
  185. if (loTail != null) {
  186. loTail.next = null;
  187. newTab[j] = loHead;
  188. }
  189. if (hiTail != null) {
  190. hiTail.next = null;
  191. newTab[j + oldCap] = hiHead;
  192. }
  193. }
  194. }
  195. }
  196. }
  197. return newTab;
  198. }
  199. public V get(Object key) {
  200. Node<K,V> e;
  201. return (e = getNode(hash(key), key)) == null ? null : e.value;
  202. }
  203. /**
  204. * 根据 hash 和 key 获取相应的 Node节点
  205. */
  206. final Node<K,V> getNode(int hash, Object key) {
  207. Node<K,V>[] tab; Node<K,V> first, e; int n; K k;
  208. // 1. 定位键值对所在桶的位置,如果该位置有元素,则获取第一个元素
  209. if ((tab = table) != null && (n = tab.length) > 0 &&
  210. (first = tab[(n - 1) & hash]) != null) {
  211. // 如果hash和key都与 第一个元素相同,则第一个元素就是我们要获取的,直接返回
  212. if (first.hash == hash &&
  213. ((k = first.key) == key || (key != null && key.equals(k))))
  214. return first;
  215. if ((e = first.next) != null) {
  216. // 2. 如果 first 是 TreeNode 类型,则调用黑红树查找方法
  217. if (first instanceof TreeNode)
  218. return ((TreeNode<K,V>)first).getTreeNode(hash, key);
  219. // 3. 对链表进行查找
  220. do {
  221. if (e.hash == hash &&
  222. ((k = e.key) == key || (key != null && key.equals(k))))
  223. return e;
  224. } while ((e = e.next) != null);
  225. }
  226. }
  227. return null;
  228. }
  229. /**
  230. * 还记HashMap底层的动态数组的定义吗 transient Node<K,V>[] table
  231. * 这里很明显是一个单向链表结构
  232. */
  233. static class Node<K,V> implements Map.Entry<K,V> {
  234. final int hash;
  235. final K key;
  236. V value;
  237. Node<K,V> next;
  238. Node(int hash, K key, V value, Node<K,V> next) {
  239. this.hash = hash;
  240. this.key = key;
  241. this.value = value;
  242. this.next = next;
  243. }
  244. public final K getKey() { return key; }
  245. public final V getValue() { return value; }
  246. public final String toString() { return key + "=" + value; }
  247. public final int hashCode() {
  248. return Objects.hashCode(key) ^ Objects.hashCode(value);
  249. }
  250. public final V setValue(V newValue) {
  251. V oldValue = value;
  252. value = newValue;
  253. return oldValue;
  254. }
  255. public final boolean equals(Object o) {
  256. if (o == this)
  257. return true;
  258. if (o instanceof Map.Entry) {
  259. Map.Entry<?,?> e = (Map.Entry<?,?>)o;
  260. if (Objects.equals(key, e.getKey()) &&
  261. Objects.equals(value, e.getValue()))
  262. return true;
  263. }
  264. return false;
  265. }
  266. }
  267. /**
  268. * JDK8 加入的 红黑树TreeNode内部类,红黑树的方法比较复杂,这里只展示一些重要的
  269. * 属性结构代码
  270. */
  271. static final class TreeNode<K,V> extends LinkedHashMap.Entry<K,V> {
  272. TreeNode<K,V> parent; // red-black tree links
  273. TreeNode<K,V> left;
  274. TreeNode<K,V> right;
  275. TreeNode<K,V> prev; // needed to unlink next upon deletion
  276. // 颜色,true红,false黑
  277. boolean red;
  278. TreeNode(int hash, K key, V val, Node<K,V> next) {
  279. super(hash, key, val, next);
  280. }
  281. }
  282. }

源码部分 结合注释还是很容易看懂的,比较复杂的是红黑树这种数据结构,以及红黑树与链表之间的相互转换。下面我们回顾下这个数据结构。

红黑树

红黑树是一种自平衡的二叉查找树,比普通的二叉查找树效率更高,它可在 O(logN) 时间内完成查找、增加、删除等操作。

普通的二叉查找树在极端情况下可退化成链表,导致 增、删、查 效率低下。红黑树通过定义一些性质,将任意节点的左右子树高度差控制在规定范围内,以达到平衡状态,红黑树的性质定义如下。

  1. 节点是红色或黑色。
  2. 根是黑色。
  3. 所有叶子都是黑色(叶子是 NIL 节点)。
  4. 每个红色节点必须有两个黑色的子节点。(从每个叶子到根的所有路径上不能有两个连续的红色节点。)
  5. 从任一节点到其每个叶子的所有简单路径都包含相同数目的黑色节点。

红黑树的操作和其他树一样,包括查找、插入、删除等,其查找过程和二叉查找树一样简单,但插入和删除操作要复杂的多,这也是其 为保持平衡性 不会退化成链表 所付出的代价。红黑树为保持平衡性 所进行的操作主要有 旋转(左旋、右旋)和变色。

红黑树的实现 确实比较复杂,光是理解其 插入、删除 的操作原理 就蛮费劲,所以这里先挖个坑,后面单独用一篇博文来分析 HashMap 的 内部类 TreeNode 对红黑树数据结构的实现。