我们在上一个章节《HashMap 原理 (一) 概念和底层架构》中讲解了 HashMap 的存储数据结构以及常用的概念及变量, 包括 capacity 容量, threshold 变量和 loadFactor 变量等. 本章主要讲解 HashMap 的扩容机制及存取原理.
先回顾一下基本概念:
table 变量: HashMap 的底层数据结构, 是 Node 类的实体数组, 用于保存 key-value 对;
capacity: 并不是一个成员变量, 但却是一个必须要知道的概念, 表示容量;
size 变量: 表示已存储的 HashMap 的 key-value 对的数量;
loadFactor 变量: 装载因子, 用于衡量满的程度;
threshold 变量: 临界值, 当超出该值时, 表示 table 表示该扩容了;
一. put 方法
HashMap 使用哈希算法得到数组中保存的位置, 然后调用 put 方法将 key-value 对保存到 table 变量中. 我们通过图来演示一下存储的过程.
简单解释一下:
1) 通过 hash(Object key) 算法得到 hash 值;
2) 判断 table 是否为 null 或者长度为 0, 如果是执行 resize() 进行扩容;
3) 通过 hash 值以及 table 数组长度得到插入的数组索引 i, 判断数组 table[i] 是否为空或为 null;
4) 如果 table[i] == null, 直接新建节点添加, 转向 8), 如果 table[i] 不为空, 转向 5);
5) 判断 table[i] 的首个元素是否和 key 一样, 如果相同直接覆盖 value, 这里的相同指的是 hashCode 以及 equals, 否则转向 6);
6) 判断 table[i] 是否为 treeNode, 即 table[i] 是否是红黑树, 如果是红黑树, 则直接在树中插入键值对, 否则转 7);
7) 遍历 table[i], 判断链表长度是否大于 8, 大于 8 的话把链表转换为红黑树, 在红黑树中执行插入操作, 否则进行链表的插入操作; 遍历过程中若发现 key 已经存在直接覆盖 value 即可;
8) 插入成功后, 判断实际存在的键值对数量 size 是否超多了最大容量 threshold, 如果超过, 进行扩容.
我们关注一下这里面最重要的三个方法, hash(),putVal(),resize().
1. hash 方法
我们通过 hash 方法计算索引, 得到数组中保存的位置, 看一下源码
- static final int hash(Object key) {
- int h;
- return (key == null) ? 0 : (h = key.hashCode()) ^ (h>>> 16);
- }
我们可以看到 HashMap 中的 hash 算法是通过 key 的 hashcode 值与其 hashcode 右移 16 位后得到的值进行异或运算得到的, 那么为什么不直接使用 key.hashCode(), 而要进行异或操作? 我们知道 hash 的目的是为了得到进行索引, 而 hash 是有可能冲突的, 也就是不同的 key 得到了同样的 hash 值, 这样就很容易产业碰撞, 如何减少这种情况的发生呢, 就通过上述的 hash(Object key) 算法将 hashcode 与 hashcode 的低 16 位做异或运算, 混合了高位和低位得出的最终 hash 值, 冲突的概率就小多了. 举个例子:
有个蒸笼, 第一层是猪肉包, 牛肉包, 鸡肉包, 第二层是白菜包, 第三层是豆沙包, 第四层是香菇包. 这时你来买早餐, 你指着第一层说除了猪肉包, 随便给我一个包子, 因为外表无法分辨, 这时拿到猪肉包的概率就有 1/3, 如果将二层, 三层, 四层与一层混合在一起了, 那么拿到猪肉包的概率就小多了.
我们的 hash(Object key) 算法一个道理, 最终的 hash 值混合了高位和低位的信息, 掺杂的元素多了, 那么最终 hash 值的随机性越大, 而 HashMap 的 table 下标依赖于最终 hash 值与 table.length()-1 的 & 运算, 这里的 & 运算类似于挑包子的过程, 自然冲突就小得多了. 计算过程如下:
最开始的 hashCode: 1111 1111 1111 1111 0100 1100 0000 1010
右移 16 位的 hashCode:0000 0000 0000 0000 1111 1111 1111 1111
异或运算后的 hash 值: 1111 1111 1111 1111 1011 0011 1111 0101
2. putVal 方法
通过 putVal 方法将传递的 key-value 对添加到数组 table 中.
- /**
- * Implements Map.put and related methods
- *
- * @param hash hash for key
- * @param key the key
- * @param value the value to put
- * @param onlyIfAbsent if true, don't change existing value
- * @param evict if false, the table is in creation mode.
- * @return previous value, or null if none
- */
- final V putVal(int hash, K key, V value, boolean onlyIfAbsent, boolean evict) {
- Node<K,V>[] tab; Node<K,V> p; int n, i;
- /**
- * 如果当前 HashMap 的 table 数组还未定义或者还未初始化其长度, 则先通过 resize() 进行扩容,
- * 返回扩容后的数组长度 n
- */
- if ((tab = table) == null || (n = tab.length) == 0)
- n = (tab = resize()).length;
- // 通过数组长度与 hash 值做按位与 & 运算得到对应数组下标, 若该位置没有元素, 则 new Node 直接将新元素插入
- if ((p = tab[i = (n - 1) & hash]) == null)
- tab[i] = newNode(hash, key, value, null);
- // 否则该位置已经有元素了, 我们就需要进行一些其他操作
- else {
- Node<K,V> e; K k;
- // 如果插入的 key 和原来的 key 相同, 则替换一下就完事了
- if (p.hash == hash && ((k = p.key) == key || (key != null && key.equals(k))))
- e = p;
- /**
- * 否则 key 不同的情况下, 判断当前 Node 是否是 TreeNode, 如果是则执行 putTreeVal 将新的元素插入
- * 到红黑树上.
- */
- else if (p instanceof TreeNode)
- e = ((TreeNode<K,V>)p).putTreeVal(this, tab, hash, key, value);
- // 如果不是 TreeNode, 则进行链表遍历
- else {
- for (int binCount = 0; ; ++binCount) {
- /**
- * 在链表最后一个节点之后并没有找到相同的元素, 则进行下面的操作, 直接 new Node 插入,
- * 但条件判断有可能转化为红黑树
- */
- if ((e = p.next) == null) {
- // 直接 new 了一个 Node
- p.next = newNode(hash, key, value, null);
- /**
- * TREEIFY_THRESHOLD=8, 因为 binCount 从 0 开始, 也即是链表长度超过 8(包含) 时,
- * 转为红黑树.
- */
- if (binCount>= TREEIFY_THRESHOLD - 1) // -1 for 1st
- treeifyBin(tab, hash);
- break;
- }
- /**
- * 如果在链表的最后一个节点之前找到 key 值相同的 (和上面的判断不冲突, 上面是直接通过数组
- * 下标判断 key 值是否相同), 则替换
- */
- 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;
- //onlyIfAbsent 为 true 时: 当某个位置已经存在元素时不去覆盖
- if (!onlyIfAbsent || oldValue == null)
- e.value = value;
- afterNodeAccess(e);
- return oldValue;
- }
- }
- ++modCount;
- // 最后判断临界值, 是否扩容.
- if (++size> threshold)
- resize();
- afterNodeInsertion(evict);
- return null;
- }
3. resize 方法
HashMap 通过 resize() 方法进行扩容, 容量规则为 2 的幂次
- /**
- * Initializes or doubles table size. If null, allocates in
- * accord with initial capacity target held in field threshold.
- * Otherwise, because we are using power-of-two expansion, the
- * elements from each bin must either stay at same index, or move
- * with a power of two offset in the new table.
- *
- * @return the table
- */
- final Node<K,V>[] resize() {
- Node<K,V>[] oldTab = table;
- int oldCap = (oldTab == null) ? 0 : oldTab.length;
- int oldThr = threshold;
- int newCap, newThr = 0;
- // 以前的容量大于 0, 也就是 hashMap 中已经有元素了, 或者 new 对象的时候设置了初始容量
- if (oldCap> 0) {
- // 如果以前的容量大于限制的最大容量 1<<30, 则设置临界值为 int 的最大值 2^31-1
- if (oldCap>= MAXIMUM_CAPACITY) {
- threshold = Integer.MAX_VALUE;
- return oldTab;
- }
- /**
- * 如果以前容量的 2 倍小于限制的最大容量, 同时大于或等于默认的容量 16, 则设置临界值为以前临界值的 2 * 倍, 因为 threshold = loadFactor*capacity,capacity 扩大了 2 倍, loadFactor 不变,
- * threshold 自然也扩大 2 倍.
- */
- else if ((newCap = oldCap <<1) < MAXIMUM_CAPACITY &&
- oldCap>= DEFAULT_INITIAL_CAPACITY)
- newThr = oldThr <<1; // double threshold
- }
- /**
- * 在 HashMap 构造器 Hash(int initialCapacity, float loadFactor) 中有一句代码, this.threshold * = tableSizeFor(initialCapacity), 表示在调用构造器时, 默认是将初始容量暂时赋值给了
- * threshold 临界值, 因此此处相当于将上一次的初始容量赋值给了新的容量. 什么情况下会执行到这句? 当调用 * 了 HashMap(int initialCapacity) 构造器, 还没有添加元素时
- */
- else if (oldThr> 0)
- newCap = oldThr;
- /**
- * 调用了默认构造器, 初始容量没有设置, 因此使用默认容量 DEFAULT_INITIAL_CAPACITY(16), 临界值
- * 就是 16*0.75
- */
- else {
- newCap = DEFAULT_INITIAL_CAPACITY;
- newThr = (int)(DEFAULT_LOAD_FACTOR * DEFAULT_INITIAL_CAPACITY);
- }
- // 对临界值做判断, 确保其不为 0, 因为在上面第二种情况 (oldThr> 0), 并没有计算 newThr
- if (newThr == 0) {
- float ft = (float)newCap * loadFactor;
- newThr = (newCap <MAXIMUM_CAPACITY && ft < (float)MAXIMUM_CAPACITY ?
- (int)ft : Integer.MAX_VALUE);
- }
- threshold = newThr;
- @SuppressWarnings({"rawtypes","unchecked"})
- /** 构造新表, 初始化表中数据 */
- Node<K,V>[] newTab = (Node<K,V>[])new Node[newCap];
- // 将刚创建的新表赋值给 table
- table = newTab;
- if (oldTab != null) {
- // 遍历将原来 table 中的数据放到扩容后的新表中来
- for (int j = 0; j <oldCap; ++j) {
- Node<K,V> e;
- if ((e = oldTab[j]) != null) {
- oldTab[j] = null;
- // 没有链表 Node 节点, 直接放到新的 table 中下标为 [e.hash & (newCap - 1)] 位置即可
- if (e.next == null)
- newTab[e.hash & (newCap - 1)] = e;
- // 如果是 treeNode 节点, 则树上的节点放到 newTab 中
- else if (e instanceof TreeNode)
- ((TreeNode<K,V>)e).split(this, newTab, j, oldCap);
- // 如果 e 后面还有链表节点, 则遍历 e 所在的链表,
- else { // 保证顺序
- Node<K,V> loHead = null, loTail = null;
- Node<K,V> hiHead = null, hiTail = null;
- Node<K,V> next;
- do {
- // 记录下一个节点
- next = e.next;
- /**
- * newTab 的容量是以前旧表容量的两倍, 因为数组 table 下标并不是根据循环逐步递增
- * 的, 而是通过 (table.length-1)& hash 计算得到, 因此扩容后, 存放的位置就
- * 可能发生变化, 那么到底发生怎样的变化呢, 就是由下面的算法得到.
- *
- * 通过 e.hash & oldCap 来判断节点位置通过再次 hash 算法后, 是否会发生改变, 如
- * 果为 0 表示不会发生改变, 如果为 1 表示会发生改变. 到底怎么理解呢, 举个例子:
- * e.hash = 13 二进制: 0000 1101
- * oldCap = 32 二进制: 0001 0000
- * & 运算: 0 二进制: 0000 0000
- * 结论: 元素位置在扩容后不会发生改变
- */
- if ((e.hash & oldCap) == 0) {
- if (loTail == null)
- loHead = e;
- else
- loTail.next = e;
- loTail = e;
- }
- /**
- * e.hash = 18 二进制: 0001 0010
- * oldCap = 32 二进制: 0001 0000
- * & 运算: 32 二进制: 0001 0000
- * 结论: 元素位置在扩容后会发生改变, 那么如何改变呢?
- * newCap = 64 二进制: 0010 0000
- * 通过 (newCap-1)&hash
- * 即 0001 1111 & 0001 0010 得 0001 0010,32+2 = 34
- */
- else {
- if (hiTail == null)
- hiHead = e;
- else
- hiTail.next = e;
- hiTail = e;
- }
- } while ((e = next) != null);
- if (loTail != null) {
- loTail.next = null;
- /**
- * 若 (e.hash & oldCap) == 0, 下标不变, 将原表某个下标的元素放到扩容表同样
- * 下标的位置上
- */
- newTab[j] = loHead;
- }
- if (hiTail != null) {
- hiTail.next = null;
- /**
- * 若 (e.hash & oldCap) != 0, 将原表某个下标的元素放到扩容表中
- * [下标 + 增加的扩容量] 的位置上
- */
- newTab[j + oldCap] = hiHead;
- }
- }
- }
- }
- }
- return newTab;
- }
二. get 方法
我们先简单说一下 get(Object key) 流程, 通过传入的 key 通过 hash() 算法得到 hash 值, 在通过 (n - 1) & hash 找到数组下标, 如果数组下标所对应的 node 值正好 key 一样就返回, 否则找到 node.next 找到下一个节点, 看是否是 treenNode, 如果是, 遍历红黑树找到对应 node, 如果不是遍历链表找到 node. 我们看一下源码
- public V get(Object key) {
- Node<K,V> e;
- // 先通过 hash(key) 找到 hash 值, 然后调用 getNode(hash,key) 找到节点
- return (e = getNode(hash(key), key)) == null ? null : e.value;
- }
- /**
- * Implements Map.get and related methods
- *
- * @param hash hash for key
- * @param key the key
- * @return the node, or null if none
- */
- final Node<K,V> getNode(int hash, Object key) {
- Node<K,V>[] tab; Node<K,V> first, e; int n; K k;
- // 通过 (n - 1) & hash 找到数组对应位置上的第一个 node
- if ((tab = table) != null && (n = tab.length)> 0 &&
- (first = tab[(n - 1) & hash]) != null) {
- // 如果这个 node 刚好 key 值相同, 直接返回
- if (first.hash == hash &&
- ((k = first.key) == key || (key != null && key.equals(k))))
- return first;
- // 如果不相同就再往下找
- if ((e = first.next) != null) {
- // 如果是 treeNode, 就遍历红黑树找到对应 node
- if (first instanceof TreeNode)
- return ((TreeNode<K,V>)first).getTreeNode(hash, key);
- // 如果是链表, 遍历链表找到对应 node
- do {
- if (e.hash == hash &&
- ((k = e.key) == key || (key != null && key.equals(k))))
- return e;
- } while ((e = e.next) != null);
- }
- }
- return null;
- }
这几个方法是核心, 虽然 HashMap 还有很多常用方法, 不过大体和这几个方法有关, 或者实现逻辑相似, 这里就不再多说了.
三. 总结
本文在上一章基本概念和底层结构的基础上, 从源码的角度讲解了扩容机制以及存取原理, 主要分析了 put 方法和 get 方法, put 方法的核心为 hash(),putVal(),resize(),get 方法的核心为 getNode(), 若有不对之处, 请批评指正, 望共同进步, 谢谢!
来源: https://www.cnblogs.com/LiaHon/p/11149644.html