HashMap原理(二) 扩容机制及存取原理 您所在的位置:网站首页 hashmap计算索引的方式 HashMap原理(二) 扩容机制及存取原理

HashMap原理(二) 扩容机制及存取原理

2024-07-13 04:51| 来源: 网络整理| 查看: 265

我们在上一个章节《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[] tab; Node 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 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)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[] resize() { Node[] oldTab = table; int oldCap = (oldTab == null) ? 0 : oldTab.length; int oldThr = threshold; int newCap, newThr = 0; //以前的容量大于0,也就是hashMap中已经有元素了,或者new对象的时候设置了初始容量 if (oldCap > 0) { //如果以前的容量大于限制的最大容量1 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[] newTab = (Node[])new Node[newCap]; //将刚创建的新表赋值给table table = newTab; if (oldTab != null) { //遍历将原来table中的数据放到扩容后的新表中来 for (int j = 0; j < oldCap; ++j) { Node 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)e).split(this, newTab, j, oldCap); //如果e后面还有链表节点,则遍历e所在的链表, else { // 保证顺序 Node loHead = null, loTail = null; Node hiHead = null, hiTail = null; Node 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 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 getNode(int hash, Object key) { Node[] tab; Node 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)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(),若有不对之处,请批评指正,望共同进步,谢谢!



【本文地址】

公司简介

联系我们

今日新闻

    推荐新闻

    专题文章
      CopyRight 2018-2019 实验室设备网 版权所有