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