HashMap原理详解

Map是用于存储键值对(<key,value>)的集合类,也可以说是一组键值对,在Java 1.8以上,HashMap的数据结果如下
img
HashMap的内部数据结构是由数组,链表,红黑树组成的。下文结合put方法的流程图解先简单分析HashMap的流程,之后再进行详细介绍。图片引用自(https://blog.csdn.net/v123411739/article/details/78996181)

1 put方法图解(总体流程认知)

1.1 在通过new HashMap<Integer,Integer>()新建一个对象时,HashMap此时的数据结构如下
在这里插入图片描述

图1-1

1.2 新建完对象后,调用put(1,1)方法时,在HashMap内部会利用key的值,计算出一个hash值,然后结合数组的长度n定位到一个数据的下标(细节的先忽略,后面再详细介绍),比如说这里通过key定位到的下标是1,这时候发现当前下标下的节点是个null对象,那么就新建一个链表类型节点(Node<K,V>)并且设置于当前下标下,如图所示
在这里插入图片描述

图1-2

1.3 若此时又调用了put(5,8),计算出来的table下标也是1(hash冲突),这个时候怎么办呢?很简单,新建多一个节点,拼接在后面不就行了?

在这里插入图片描述

图1-3

1.4 又到了后面,我们不断调用put方法,计算出来的下标都是1,此时链表的长度很长了,难道一直往链表尾部添加节点,这时候会出现问题?当你调用get方法根据key获取一个value的时候,假如运气不好,就是查找尾部的节点,那要遍历整条链表,这时候效率非常低,因此,HashMap会在链表长度为8的时候,将链表转换成红黑树,此时可能的结构如下(后面的图省略value部分)。
转成红黑树后,红黑树的节点按照key自然排序,或者然后Comparable/Comparator方法定义的规则进行排序,那么后续的如果进行查找的话,只需要根据红黑树进行查找,效率非常高,时间复杂度达到log2(n)。

在这里插入图片描述

图1-4

1.5 转换成红黑树后,再调用put方法进行添加节点的话,首选需要在红黑树进行查找,然后找到合适的位置进行替换值或者插入
在这里插入图片描述

图1-5

1.6 然后我们又不断调用put方法,这个时候整个HashMap的节点数比较多了,会出现什么问题?当然后有的链表长或者红黑树过高了,这个时候就要对HashMap进行扩容了,Map默认是达到0.75 * n的节点数时触发扩容在。

从这5个步骤中,我们引出了几个问题

  1. Map中数组的长度是怎么计算的?
  2. Map是怎么通过key值定位到数组下表的?
  3. Map解决Hash冲突运用了什么方式?
  4. Map具体是怎么扩容的,什么时候触发扩容,细节是怎么样的?
  5. 为什么时0.75 * n的时候触发扩容

2 细节分析

先看一下HashMap中的几个参数

	// 数组
    transient Node<K,V>[] table;
    // 节点数(链表节点+红黑树节点)
    transient int size;
    // 修改次数
    transient int modCount;
    // 促发扩容的节点数大小,如果是新建状态,那么这个字段代表的是当前数组最大容量
    int threshold;
    // 加载因子,默认0.75
    final float loadFactor;

2.1 Map中数组的长度是怎么计算的?

  1. HashMap新建时如果不指定容量,那么默认的table数组长度时16。
  2. HashMap新建时如果指定了容量参数,比如30,那么计算出第一个大于等于指定容量、属于2的k次方的值作为table的容量,比如30的话会计算出32。

换而言之,HashMap的容量一定是2的k次方,假如当前table的长度为n,每次扩容时数组的长度增长到2*n。计算的算法比较巧妙,推荐大家看一下这位大神的文章HashMap容量计算

2.2 HashMap如何通过Key值定位数组下标?

    static final int hash(Object key) {
        int h;
        return (key == null) ? 0 : (h = key.hashCode()) ^ (h >>> 16);
    }

如上代码所示,HashMap是key的hashCode跟hashCode的高16位置做异或操作,最终算出一个hash值,可能看的有点拗口,直接看例子

h               10100000000001100000000000000101
h>>>16          00000000000000001010000000000110
h ^ h>>>16      10100000000001101010000000000011

拿到计算出来的hash值后,就可以算出对应的table数组下标

// n代表的是数组的长度
(n - 1) & hash

HashMap通过上面的公式算出对应数组的下标,比如现在table数组的长度是16,那么(n-1)对应的二进制就是

0000000000000000001000000000001111

可以看到最终节点对应的table数组下标只跟低4位有关,所以这就说明了为什么key明明有hashCode,却还要做特殊的移位运算,因为这样可以尽量避免hash冲突。

2.3 在HashMap里面这种解决hash冲突的方法叫做链地址法,除了链地址法还有那些方法也可以解决hash冲突呢?

  1. 开放定址法(线性探测再散列,二次探测再散列,伪随机探测再散列)
  2. 再哈希法
  3. 建立一个公共溢出区

2.4 HashMap是怎么扩容的,回到1.5步骤中,当HashMap中的节点数大于 0.75 * 16时,那么就会触发扩容,如何扩容呢?

HashMap会新建一个2*n长度的newTable数组,然后把table[i]下标下的链表或者红黑树一拆为2,把n & hash == 0 的节点放到新数组table[i]下标下,把n & hash == 1的节点移动至新数组table[i+n]的下标下,最后用新数组替换旧数组,如下图2-1所示
在这里插入图片描述

图2-1
如前文2.2所说,节点位于数组的下标是通过(n-1)& hash计算出来的,就拿n=16为一个例子来说
扩容前,n = 16, 那么n-1的二进制位如下
0000000000000000001000000000001111
n 的二进制位如下
0000000000000000000000000000010000
扩容后,新数组长度n=32,那么n-1的二进制位如下
0000000000000000001000000000011111

显而易见,当 n & hash == 0 的时候,hash的第五位为0,此时
(n-1& hash == (2n -1) & hash
当n & hash == 1的时候,hash的第五位为1,此时
(n-1& hash + n ==  (2n -1) & hash

扩容的过程顺带说明了为什么HashMap每次选择两倍扩容,因为选择两倍扩容不需要再对节点重新根据hash值计算下标,只需要根据上述操作相应的把节点移动到newTable[i] 或者 newTable[i+n]下标下,避免了大量节点的重hash过程,效率上会比较好。

2.5 为什么时0.75 * n的时候触发扩容?

提高空间利用率和减少查询成本的折中,主要是泊松分布,0.75的话碰撞最小,关于泊松分布过于复杂,这里不再陈述,有兴趣的可以自行百度或者Google查看。说白了就是如果负载因子配的过低,比如0.5,0.4,那么HashMap的空间利用率不足,可能会造成很多数组下标下节点为空或者都是短链表,如果过高的话,那又可能红黑树过高或者链表长,造成查询效率降低。

3 put 代码分析

理解了上文put方法的过程再分析代码就轻松了许多了。

    /**
     * Associates the specified value with the specified key in this map.
     * If the map previously contained a mapping for the key, the old
     * value is replaced.
     *
     * @param key key with which the specified value is to be associated
     * @param value value to be associated with the specified key
     * @return the previous value associated with <tt>key</tt>, or
     *         <tt>null</tt> if there was no mapping for <tt>key</tt>.
     *         (A <tt>null</tt> return can also indicate that the map
     *         previously associated <tt>null</tt> with <tt>key</tt>.)
     */
    public V put(K key, V value) {
        return putVal(hash(key), key, value, false, true);
    }

    /**
     * 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;
        // 如果table为空或者table的length等于0,那么调用resize方法进行初始化
        // 即新建table
        if ((tab = table) == null || (n = tab.length) == 0)
            n = (tab = resize()).length;
        // 通过(n - 1) & hash 定位头节点下标并且获取到头节点,赋值给p,如果p为空,那么直接新建一个链表类型节点,赋值给头节点
        if ((p = tab[i = (n - 1) & hash]) == null)
            tab[i] = newNode(hash, key, value, null);
        else {
            Node<K,V> e; K k;
            // 如果头节点p的hash和传入的hash相等并且p节点的key和传入的key相等,那么即为目标节点,把p赋值给e
            if (p.hash == hash &&
                ((k = p.key) == key || (key != null && key.equals(k))))
                e = p;
            // 如果头节点p不是目标节点并且p是红黑树类型节点,那么调用红黑树putTreeVal方法进行put
            else if (p instanceof TreeNode)
                e = ((TreeNode<K,V>)p).putTreeVal(this, tab, hash, key, value);
            else {
                // 遍历链表
                for (int binCount = 0; ; ++binCount) {
                    // 如果遍历到了链表尾部,没有与传入的hash和key相对应的节点,那么新建一个链表类型节点,添加到链表尾部
                    if ((e = p.next) == null) {
                        p.next = newNode(hash, key, value, null);
                        // 如果链表中的节点数目大于阈值(8), 那么调用treeifyBin方法将链表转换成红							黑树
                        if (binCount >= TREEIFY_THRESHOLD - 1) // -1 for 1st
                            treeifyBin(tab, hash);
                        break;
                    }
                    // 如果节点e的hash和传入的hash相等并且e节点的key和传入的key相等,那么即为目标节点,跳出循环
                    if (e.hash == hash &&
                        ((k = e.key) == key || (key != null && key.equals(k))))
                        break;
                    // 把p赋值给e
                    p = e;
                }
            }
            // 如果e节点不为空,那么证明与传入的hash和key相对应的节点存在,用value覆盖掉e节点的value即可,并且返回oldValue
            if (e != null) { // existing mapping for key
                V oldValue = e.value;
                if (!onlyIfAbsent || oldValue == null)
                    e.value = value;
                afterNodeAccess(e);
                return oldValue;
            }
        }
        ++modCount;
        // 如果当前节点数大于扩容阈值,那么进行扩容
        if (++size > threshold)
            resize();
        // 空的钩子方法, 在LinkedHashMap等会用到
        afterNodeInsertion(evict);
        return null;
    }
        /**
         * Tree version of putVal.
         */
        final TreeNode<K,V> putTreeVal(HashMap<K,V> map, Node<K,V>[] tab,
                                       int h, K k, V v) {
            Class<?> kc = null;
            boolean searched = false;
            // 把红黑树得根节点赋值给root
            TreeNode<K,V> root = (parent != null) ? root() : this;
            // 把root赋值给p
            for (TreeNode<K,V> p = root;;) {
                int dir, ph; K pk;
                // 把p.hash赋值给ph,并且判断p.hash是否比传入的h大,如果是,把dir赋值为-1,即下一步往红黑树的左子树进行查找
                if ((ph = p.hash) > h)
                    dir = -1;
                // 判断ph是否小于h,把dir赋值为1,即下一步往右子树查找
                else if (ph < h)
                    dir = 1;
                // 如果传入的hash和p节点的hash相等,并且传入的key和p节点的key相等,那么为目标节点直接返回
                else if ((pk = p.key) == k || (k != null && k.equals(pk)))
                    return p;
                // 判断传入的key是否实现了comparable接口,如果有,返回k的泛型类型Class对象给kc,如果,kc == null, 或者p的key和k相等,那么继续执行 
                else if ((kc == null &&
                          (kc = comparableClassFor(k)) == null) ||
                         (dir = compareComparables(kc, k, pk)) == 0) {
                    // 如果是循环第一次进行查找
                    if (!searched) {
                        TreeNode<K,V> q, ch;
                        searched = true;
                        // 先查询左子树是否有目标对象,否则,查询右子树是否有目标对象,为什么第二次第三次查询不需要,因为第一次查询符合上述if条件后,会往左或者往右走,往子树走,既然在上层找过一次之后没有,那么再往下层走了之后就肯定没有了
                        if (((ch = p.left) != null &&
                             (q = ch.find(h, k, kc)) != null) ||
                            ((ch = p.right) != null &&
                             (q = ch.find(h, k, kc)) != null))
                            return q;
                    }
                    // 通过一种规则生成dir方向
                    dir = tieBreakOrder(k, pk);
                }

                TreeNode<K,V> xp = p;
                // 如果p为空,那么证明没有目标节点,要新插入
                if ((p = (dir <= 0) ? p.left : p.right) == null) {
                    // 把xp.next 赋值给xpn
                    Node<K,V> xpn = xp.next;
                    // 新建红黑树节点
                    TreeNode<K,V> x = map.newTreeNode(h, k, v, xpn);
                    // 如果dir < 0 ,插入左子节点
                    if (dir <= 0)
                        xp.left = x;
                    // 否则插入右子节点
                    else
                        xp.right = x;
                    // 在 xp 和 xpn 链表中间插入x
                    xp.next = x;
                    x.parent = x.prev = xp;
                    if (xpn != null)
                        ((TreeNode<K,V>)xpn).prev = x;
                    // 插入后平衡红黑树,并且把红黑树的头节点刚到头节点位置处
                    moveRootToFront(tab, balanceInsertion(root, x));
                    return null;
                }
            }
        }
    /**
     * Replaces all linked nodes in bin at index for given hash unless
     * table is too small, in which case resizes instead.
     */
    final void treeifyBin(Node<K,V>[] tab, int hash) {
        int n, index; Node<K,V> e;
        // 如果tab 为空或者tab.length 小于最小长度,那么用resize方法进行扩容
        if (tab == null || (n = tab.length) < MIN_TREEIFY_CAPACITY)
            resize();
        // 如果头节点不为空
        else if ((e = tab[index = (n - 1) & hash]) != null) {
            TreeNode<K,V> hd = null, tl = null;
            do {
                // 新建红黑树节点
                TreeNode<K,V> p = replacementTreeNode(e, null);
                // 拼接链表
                if (tl == null)
                    hd = p;
                else {
                    p.prev = tl;
                    tl.next = p;
                }
                tl = p;
            } while ((e = e.next) != null);
            // 如果hd节点不为空,把hd赋值给头节点,并且调用treeify方法进行红黑树转换
            if ((tab[index] = hd) != null)
                hd.treeify(tab);
        }
    }
        /**
         * Forms tree of the nodes linked from this node.
         */
		// 通过 treeifyBin 方法的操作,tab现在保持着链表结构
        final void treeify(Node<K,V>[] tab) {
            TreeNode<K,V> root = null;
            // 首次循环把this即调用节点赋值给x,以后每次循环把 x.next 赋值给 x
            for (TreeNode<K,V> x = this, next; x != null; x = next) {
                // 把 x.next 赋值给 next
                next = (TreeNode<K,V>)x.next;
                x.left = x.right = null;
                // 如果root == null, 也就是循环第一次调用,那么把x.parent 设为空,把x.red 设为false表示为黑节点, 把当前节点x赋值给root
                if (root == null) {
                    x.parent = null;
                    x.red = false;
                    root = x;
                }
                else {
                    // 把x节点的key赋值给k
                    K k = x.key;
                    // 把x节点的hash赋值给h
                    int h = x.hash;
                    Class<?> kc = null;
                    // 从根节点开始往下确定位置插入
                    for (TreeNode<K,V> p = root;;) {
                        int dir, ph;
                        K pk = p.key;
                        // 往左子树走
                        if ((ph = p.hash) > h)
                            dir = -1;
                        // 往右子树走
                        else if (ph < h)
                            dir = 1;
                        // 判断k是否实现了comparable接口,如果有,返回k的泛型类型Class对象给kc,如果,kc == null, 或者pk和k相等,那么继续执行 
                        else if ((kc == null &&
                                  (kc = comparableClassFor(k)) == null) ||
                                 (dir = compareComparables(kc, k, pk)) == 0)
                            // 通过某个规则定义方向
                            dir = tieBreakOrder(k, pk);
						// 把p赋值给xp
                        TreeNode<K,V> xp = p;
                        // 如果dir<=0 把p.left 赋值为p,否则把p.right 赋值给p,如果p == null,那么进行插入
                        if ((p = (dir <= 0) ? p.left : p.right) == null) {
                            // 设置xp为x的parent
                            x.parent = xp;
                            // 如果dir<=0, 插入xp的左边
                            if (dir <= 0)
                                xp.left = x;
                            // 如果dir,插入xp的右边
                            else
                                xp.right = x;
                            // 插入后对红黑树进行平衡
                            root = balanceInsertion(root, x);
                            break;
                        }
                    }
                }
            }
            // 把root节点移到头节点处
            moveRootToFront(tab, root);
        }
        /**
         * Ensures that the given root is the first node of its bin.
         */
        static <K,V> void moveRootToFront(Node<K,V>[] tab, TreeNode<K,V> root) {
            int n;
            // 判断root,tab 是否等于null,并且tab.length >0
            // 将tab.length 赋值给n
            if (root != null && tab != null && (n = tab.length) > 0) {
                // 计算root节点的hash并且赋值给index
                int index = (n - 1) & root.hash;
                // 当前的头节点赋值给first
                TreeNode<K,V> first = (TreeNode<K,V>)tab[index];
                // 如果root和first不是同一个节点
                if (root != first) {
                    Node<K,V> rn;
                    // root赋值给头节点
                    tab[index] = root;
                    // root 前一个节点的next 指向root节点的next
                    // root 下一个节点的prev 指向root节点的pre
                    TreeNode<K,V> rp = root.prev;
                    if ((rn = root.next) != null)
                        ((TreeNode<K,V>)rn).prev = rp;
                    if (rp != null)
                        rp.next = rn;
                    // 原头节点的prev 指向root
                    if (first != null)
                        first.prev = root;
                    // root节点的next指向原头节点
                    root.next = first;
                    root.prev = null;
                }
                // 
                assert checkInvariants(root);
            }
        }
    /**
     * 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;
        if (oldCap > 0) {
            // 查找老表容量是否已经达到了最大值, MAXIMUM_CAPACITY = 1<<30, 如果超过
            // 将阈值直接设置为 Integer.MAX_VALUE 并且返回老表
            if (oldCap >= MAXIMUM_CAPACITY) {
                threshold = Integer.MAX_VALUE;
                return oldTab;
            }
            // 将新表容量newcap设置为老表容量的两倍,如果newcap 小于最大值,并且oldcap > 16 
            // 将新阈值设置为老阈值的两倍
            else if ((newCap = oldCap << 1) < MAXIMUM_CAPACITY &&
                     oldCap >= DEFAULT_INITIAL_CAPACITY)
                newThr = oldThr << 1; // double threshold
        }
        // 如果老表容量小于等于0,即为第一次初始化HashMap,把老表阈值赋值给newcap
        else if (oldThr > 0) // initial capacity was placed in threshold
            newCap = oldThr;
        // 如果老表容量和阈值都小于等于0,那么newcap和newThr都设置为默认值
        else {               // zero initial threshold signifies using defaults
            newCap = DEFAULT_INITIAL_CAPACITY;
            newThr = (int)(DEFAULT_LOAD_FACTOR * DEFAULT_INITIAL_CAPACITY);
        }
        // 如果newThr(新阈值等于0),那么通过老表容量 * 新负载因子获取新阈值
        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 = newTab;
        // 如果老表不为空,遍历老表
        if (oldTab != null) {
            for (int j = 0; j < oldCap; ++j) {
                Node<K,V> e;
                if ((e = oldTab[j]) != null) {
                    oldTab[j] = null;
                    // 如果老表头节点不为空,但是没有next元素,即这个头节点下结构为链表类型
                    // 并且只有一个节点,那么直接用新表容量计算下表,设置新表对应头节点
                    if (e.next == null)
                        newTab[e.hash & (newCap - 1)] = e;
                    // 如果是红黑树节点,那么调用红黑树的split方法进行操作
                    else if (e instanceof TreeNode)
                        ((TreeNode<K,V>)e).split(this, newTab, j, oldCap);
                    // 如果是链表,将老表当前头节点开始的链表拆分成两条,假设链表中的节点为e
                    // e.hash & oldcap == 0 的节点拼接成一条链表 loHead
                    // e.hash & oldcap == 1 的节点拼接成一条链表 hiHead
                    // 把新表newTab[j] 的头节点直接设置为 e1的头节点
                    // 把新表newTab[j + oldcap] 的头节点直接设置为 e2的头节点
                    // 具体代码易读不解析
                    else { // preserve order
                        Node<K,V> loHead = null, loTail = null;
                        Node<K,V> hiHead = null, hiTail = null;
                        Node<K,V> next;
                        do {
                            next = e.next;
                            if ((e.hash & oldCap) == 0) {
                                if (loTail == null)
                                    loHead = e;
                                else
                                    loTail.next = e;
                                loTail = e;
                            }
                            else {
                                if (hiTail == null)
                                    hiHead = e;
                                else
                                    hiTail.next = e;
                                hiTail = e;
                            }
                        } while ((e = next) != null);
                        if (loTail != null) {
                            loTail.next = null;
                            newTab[j] = loHead;
                        }
                        if (hiTail != null) {
                            hiTail.next = null;
                            newTab[j + oldCap] = hiHead;
                        }
                    }
                }
            }
        }
        return newTab;
    }
        /**
         * Splits nodes in a tree bin into lower and upper tree bins,
         * or untreeifies if now too small. Called only from resize;
         * see above discussion about split bits and indices.
         *
         * @param map the map
         * @param tab the table for recording bin heads
         * @param index the index of the table being split
         * @param bit the bit of hash to split on
         */
        // 在链表转成红黑树后,依然保留着一条链表结构,但节点类型时红黑树节点
        final void split(HashMap<K,V> map, Node<K,V>[] tab, int index, int bit) {
            TreeNode<K,V> b = this;
            // Relink into lo and hi lists, preserving order
            TreeNode<K,V> loHead = null, loTail = null;
            TreeNode<K,V> hiHead = null, hiTail = null;
            int lc = 0, hc = 0;
            // 按照红黑树保留的链表结构从头遍历,假设任意节点为e
            // e.hash & oldcap == 0 的节点拼接成一条链表 loHead
            // e.hash & oldcap == 1 的节点拼接成一条链表 hiHead
            // 两条链表节点类型为TreeNode,即红黑树节点类型
            for (TreeNode<K,V> e = b, next; e != null; e = next) {
                next = (TreeNode<K,V>)e.next;
                e.next = null;
                if ((e.hash & bit) == 0) {
                    if ((e.prev = loTail) == null)
                        loHead = e;
                    else
                        loTail.next = e;
                    loTail = e;
                    ++lc;
                }
                else {
                    if ((e.prev = hiTail) == null)
                        hiHead = e;
                    else
                        hiTail.next = e;
                    hiTail = e;
                    ++hc;
                }
            }
			// 如果loHead不为空
            if (loHead != null) {
                // 如果以loHead长度小于8,那么恢复成Node类型的链表
                if (lc <= UNTREEIFY_THRESHOLD)
                    tab[index] = loHead.untreeify(map);
                // 否则,转换成红黑树
                else {
                    tab[index] = loHead;
                    if (hiHead != null) // (else is already treeified)
                        loHead.treeify(tab);
                }
            }
            if (hiHead != null) {
                // 如果以hiHead长度小于8,那么恢复成Node类型的链表
                if (hc <= UNTREEIFY_THRESHOLD)
                    tab[index + bit] = hiHead.untreeify(map);
                // 否则,转换成红黑树
                else {
                    tab[index + bit] = hiHead;
                    if (loHead != null)
                        hiHead.treeify(tab);
                }
            }
        }
        /**
         * Returns a list of non-TreeNodes replacing those linked from
         * this node.
         */
        final Node<K,V> untreeify(HashMap<K,V> map) {
            Node<K,V> hd = null, tl = null;
            // 从当前红黑树头节点开始,按照保持的链表结构遍历
            for (Node<K,V> q = this; q != null; q = q.next) {
                // 新建Node类型节点
                Node<K,V> p = map.replacementNode(q, null);
                // 拼接新类型链表
                if (tl == null)
                    hd = p;
                else
                    tl.next = p;
                tl = p;
            }
            return hd;
        }

4 get代码分析

    /**
     * Returns the value to which the specified key is mapped,
     * or {@code null} if this map contains no mapping for the key.
     *
     * <p>More formally, if this map contains a mapping from a key
     * {@code k} to a value {@code v} such that {@code (key==null ? k==null :
     * key.equals(k))}, then this method returns {@code v}; otherwise
     * it returns {@code null}.  (There can be at most one such mapping.)
     *
     * <p>A return value of {@code null} does not <i>necessarily</i>
     * indicate that the map contains no mapping for the key; it's also
     * possible that the map explicitly maps the key to {@code null}.
     * The {@link #containsKey containsKey} operation may be used to
     * distinguish these two cases.
     *
     * @see #put(Object, Object)
     */
    public V get(Object key) {
        Node<K,V> e;
        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;
        // 判断table是否为空,并且table.length是否大于0
        // 通过n - 1 & hash 找到头节点下标并且找出头节点
        if ((tab = table) != null && (n = tab.length) > 0 &&
            (first = tab[(n - 1) & hash]) != null) {
            // 如果first节点(头节点)的 hash 和 key 和 入参的hash 还有key相同,则first为目标节				点,直接返回
            if (first.hash == hash && // always check first node
                ((k = first.key) == key || (key != null && key.equals(k))))
                return first;
            // 如果first的next不为空
            if ((e = first.next) != null) {
                // 如果first节点是红黑树节点,那么调用红黑树的getTreeNode方法进行查找
                if (first instanceof TreeNode)
                    return ((TreeNode<K,V>)first).getTreeNode(hash, key);
                // 否则,对链表进行遍历查找
                do {
                    if (e.hash == hash &&
                        ((k = e.key) == key || (key != null && key.equals(k))))
                        return e;
                } while ((e = e.next) != null);
            }
        }
        return null;
    }

        /**
         * Calls find for root node.
         */
        final TreeNode<K,V> getTreeNode(int h, Object k) {
            // 通过root方法找到红黑树头节点,进行遍历查找
            return ((parent != null) ? root() : this).find(h, k, null);
        }
        /**
         * Finds the node starting at root p with the given hash and key.
         * The kc argument caches comparableClassFor(key) upon first use
         * comparing keys.
         */
        final TreeNode<K,V> find(int h, Object k, Class<?> kc) {
            // 将当前调用节点赋值给p
            TreeNode<K,V> p = this;
            do {
                int ph, dir; K pk;
                // 将p的左节点赋值给pl,右节点赋值给pr
                TreeNode<K,V> pl = p.left, pr = p.right, q;
                // 如果p节点hash 值大于传入的hash值,那么把pl赋值给p(向左遍历)
                if ((ph = p.hash) > h)r
                    p = pl;
                // 如果p节点hash 值小于传入的hash值,那么把pr赋值给p(向右遍历)
                else if (ph < h)
                    p = pr;
                // 如果p节点hash值等于传入的hash值,并且p节点的key等于传入的key,那么p为目标节点,直				接返回
                else if ((pk = p.key) == k || (k != null && k.equals(pk)))
                    return p;
                // 如果p的左节点为空,那么把pr赋值给p(向右遍历)
                else if (pl == null)
                    p = pr;
                // 如果p的右节点为空,那么把pl赋值给p(向左遍历)
                else if (pr == null)
                    p = pl;
                // 调用comparableClassFor 判断传入的key k是否有实现Comparable接口,如果有,那么返					回k泛型参数的Class类型,并且调用compareComparables方法,通过Comparable的						 compareTo方法判断p节点的key和入参k的大小关系,判断方向
                else if ((kc != null ||
                          (kc = comparableClassFor(k)) != null) &&
                         (dir = compareComparables(kc, k, pk)) != 0)
                    // dir < 0 则向左遍历,否则向右遍历
                    p = (dir < 0) ? pl : pr;
                // 上述条件都不满足的话,那么查询右子树,如果右子树有对应节点,那么直接返回
                else if ((q = pr.find(h, k, kc)) != null)
                    return q;
                // pl赋值给p(向左遍历)
                else
                    p = pl;
            } while (p != null);
            return null;
        }

5 remove代码分析

    /**
     * Implements Map.remove and related methods.
     *
     * @param hash hash for key
     * @param key the key
     * @param value the value to match if matchValue, else ignored
     * @param matchValue if true only remove if value is equal
     * @param movable if false do not move other nodes while removing
     * @return the node, or null if none
     */
    final Node<K,V> removeNode(int hash, Object key, Object value,
                               boolean matchValue, boolean movable) {
        Node<K,V>[] tab; Node<K,V> p; int n, index;
        // 判断tab是否为空并且length是否大于0,获取到头节点p
        if ((tab = table) != null && (n = tab.length) > 0 &&
            (p = tab[index = (n - 1) & hash]) != null) {
            Node<K,V> node = null, e; K k; V v;
            // 如果头节点就是要删除的目标节点,赋值p给node
            if (p.hash == hash &&
                ((k = p.key) == key || (key != null && key.equals(k))))
                node = p;
            else if ((e = p.next) != null) {
                // 如果头节点是红黑树类型,调用红黑树getTreeNode方法查找要删除的目标节点
                if (p instanceof TreeNode)
                    node = ((TreeNode<K,V>)p).getTreeNode(hash, key);
                // 如果头节点是链表节点类型,那么遍历链表查找要删除的目标节点
                else {
                    do {
                        if (e.hash == hash &&
                            ((k = e.key) == key ||
                             (key != null && key.equals(k)))) {
                            node = e;
                            break;
                        }
                        p = e;
                    } while ((e = e.next) != null);
                }
            }
            // 如果目标节点存在
            if (node != null && (!matchValue || (v = node.value) == value ||
                                 (value != null && value.equals(v)))) {
                // 如果要删除的节点是红黑树节点,那么调用红黑树removeTreeNode方法进行删除
                if (node instanceof TreeNode)
                    ((TreeNode<K,V>)node).removeTreeNode(this, tab, movable);
                // 如果要删除的节点是链表类型节点,并且是头节点,那么头节点直接设置为node的next节点
                else if (node == p)
                    tab[index] = node.next;
                // 如果要删除的节点是链表类型节点,并且不是头节点,那么进行常规链表删除
                // p为目标节点的前一个节点
                else
                    p.next = node.next;
                ++modCount;
                --size;
                afterNodeRemoval(node);
                return node;
            }
        }
        return null;
    }

        /**
         * Removes the given node, that must be present before this call.
         * This is messier than typical red-black deletion code because we
         * cannot swap the contents of an interior node with a leaf
         * successor that is pinned by "next" pointers that are accessible
         * independently during traversal. So instead we swap the tree
         * linkages. If the current tree appears to have too few nodes,
         * the bin is converted back to a plain bin. (The test triggers
         * somewhere between 2 and 6 nodes, depending on tree structure).
         */
        final void removeTreeNode(HashMap<K,V> map, Node<K,V>[] tab,
                                  boolean movable) {
            int n;
            // 判断tab是否为空
            if (tab == null || (n = tab.length) == 0)
                return;
            // ---start---
            // 从这个start开始到下个end的步骤其实是在维护红黑树中的链表节点,即对链表进行删除
            int index = (n - 1) & hash;
            // first:头节点 root: 树头节点
            TreeNode<K,V> first = (TreeNode<K,V>)tab[index], root = first, rl;
            // succ:当前节点(目标删除节点的next节点) pred:当前节点的上一个节点
            TreeNode<K,V> succ = (TreeNode<K,V>)next, pred = prev;
            // 如果pred节点为空,那么当前节点是勾结点,那么把succ设置给头节点
            if (pred == null)
                tab[index] = first = succ;
            // 如果pred不空,那么pred的下一个节点为目标节点的next节点
            else
                pred.next = succ;
            // 如果succ不空,那么succ节点的前一个节点为目标节点的前一个节点
            if (succ != null)
                succ.prev = pred;
            // 如果first为空,那么当前树为空,直接返回
            if (first == null)
                return;
            // 如果root.parent 不为空,那么重新赋值
            if (root.parent != null)
                root = root.root();
            // 如果树太小,那么直接转链表返回
            if (root == null
                || (movable
                    && (root.right == null
                        || (rl = root.left) == null
                        || rl.left == null))) {
                tab[index] = first.untreeify(map);  // too small
                return;
            }
            // ---end--- 
            TreeNode<K,V> p = this, pl = left, pr = right, replacement;
            //  如果目标删除节点的左节点和右节点都不为空
            //  交换p节点和s(p右子树key最小值节点)节点的位置
            if (pl != null && pr != null) {
                TreeNode<K,V> s = pr, sl;
                // 从p节点的右节点开始,一直往左遍历,找到p节点右子树的key最小值节点
                // 最小值节点为s
                while ((sl = s.left) != null) // find successor
                    s = sl;
                // 交换p节点和s节点的颜色
                boolean c = s.red; s.red = p.red; p.red = c; // swap colors
                TreeNode<K,V> sr = s.right;
                TreeNode<K,V> pp = p.parent;
                // 如果s节点等于p节点的右节点,即p节点的右节点没有左子树
                if (s == pr) { // p was s's direct parent
                    // 把p的parent设置成s
                    p.parent = s;
                    // 把s的右节点设置成p
                    s.right = p;
                }
                // 如果s节点不等于p节点的右节点,即p节点的右节点有左子树
                else {
                    TreeNode<K,V> sp = s.parent;
                    // 把s父节点的左节点或者右节点赋值为p
                    if ((p.parent = sp) != null) {
                        if (s == sp.left)
                            sp.left = p;
                        else
                            sp.right = p;
                    }
                    // 把s的右节点赋值成p节点的右节点
                    if ((s.right = pr) != null)
                        pr.parent = s;
                }
                // 直接把p.left 设置为空,因为s的左节点为空,交换之后p的左节点应该叶微孔
                p.left = null;
                // 把s的右节点赋值给p的右节点
                if ((p.right = sr) != null)
                    sr.parent = p;
                // 把p的左节点赋值给s的左节点
                if ((s.left = pl) != null)
                    pl.parent = s;
                // 把p的父节点这是给s的父节点,如果为空,那么pp就是root节点
                if ((s.parent = pp) == null)
                    root = s;
                // 否则把s赋值给pp节点的左节点或者右节点
                else if (p == pp.left)
                    pp.left = s;
                else
                    pp.right = s;
                // 如果sr不为空,那么replacement=sr
                if (sr != null)
                    replacement = sr;
                // 否则replacement = p;
                else
                    replacement = p;
            }
            // p的右子树为空
            // replacement 等于p的左节点
            else if (pl != null)
                replacement = pl;
            // p的左子树为空
            // replacement 等于p的右节点
            else if (pr != null)
                replacement = pr;
            else
                replacement = p;
            // 如果replacement != p,即对应原始p的右节点pr有左子树
            // 把交换后的父节点从树中删除
            if (replacement != p) {
                // replacement的父节点等于p的父节点
                TreeNode<K,V> pp = replacement.parent = p.parent;
                // 如果pp是空,那么root就是replacement节点
                if (pp == null)
                    root = replacement;
                // 否则把replacement赋值给pp的左子节点或者右子节点
                else if (p == pp.left)
                    pp.left = replacement;
                else
                    pp.right = replacement;
                p.left = p.right = p.parent = null;
            }

            // 删除后进行平衡处理,查看红黑树原理
            TreeNode<K,V> r = p.red ? root : balanceDeletion(root, replacement);

            // 如果replacement == p,p节点左右子树都为空,或者p节点的右子节点没有左右子树
            if (replacement == p) {  // detach
                TreeNode<K,V> pp = p.parent;
                p.parent = null;
                if (pp != null) {
                    if (p == pp.left)
                        pp.left = null;
                    else if (p == pp.right)
                        pp.right = null;
                }
            }
            if (movable)
                moveRootToFront(tab, r);
        }
  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值