首页 > 编程语言 >学会HashMap源码,一篇就够了

学会HashMap源码,一篇就够了

时间:2024-03-24 23:59:01浏览次数:19  
标签:hash HashMap tab int 就够 源码 key null 节点

目录

 一.数据结构

  1.数组

2.链表

3.哈希表

(1)什么是哈希?

(2)哈希算法的特点

(3)哈希表

(4)什么是哈希冲突?怎么解决

(5)HashMap是怎么解决哈希冲突的?

4.红黑树

(1)什么是树

(2)什么是二叉树

(3)什么是二叉搜索树

(4)二叉搜索树的缺点

(5)AVL树

(6)红黑树

    一. 介绍

二.查找操作

三.插入操作

场景1:红黑树为空树

场景2:插入节点的Key已经存在

场景3:插入节点的父节点为黑色

场景4:插入节点的父节点为红色,分五种情况

四.删除操作

(7)HashMap中使用红黑树而不是AVL树的原因

5.HashMap中使用的数据结构

二.源码分析

1.Node结构

2.属性

3.构造器

 4.put方法

5.resize()扩容方法

6.get()方法

7.remove()方法

8.全部源码

三.问题

1.HashMap1.7和1.8的区别

2.HashMap1.8为什么改为尾插法?

3.HashMap1.7循环链表问题


 一.数据结构

 1.数组

  数组是按照一定顺序排列的相同类型的元素集合,在内存中是连续存储的,可以通过下标直接访问数组中的元素。

优点:

1.直接访问:由于数组中的元素在内存中是连续存储的,因此可以通过下标直接访问数组中的元素,访问效率高。

缺点: 

1.固定长度:数组在创建时需要指定长度,长度固定,无法动态调整。如果需要存储的元素数量超过数组长度,就需要重新创建一个更大的数组,并将原数组中的元素复制过去,造成内存浪费和性能损失。
2.插入和删除元素效率低:由于数组的长度固定且元素在内存中连续存储,插入和删除元素都需要移动其他元素的位置,效率较低。

2.链表

链表是由一系列节点组成,每个节点包含数据项和一个指向下一个节点的引用。链表中的节点并不是连续存储的,而是通过指针进行连接。

链表的优点:

1.插入和删除操作效率高:由于链表的节点并不是连续存储的,所以在链表中插入和删除一个节点的操作只需要修改相邻节点的指针,效率较高。
2.动态性:链表的长度可以根据需要动态地增长或缩小,不需要预先分配内存空间。
3.空间利用率高:链表可以灵活分配内存,且不会浪费额外的内存。


链表的缺点:

1.随机访问效率低:链表中的节点并不是连续存储的,不能像数组一样通过下标直接访问元素,只能从头节点开始依次遍历,所以随机访问元素的效率较低。
2.内存消耗较大:由于每个节点都需要存储指向下一个节点的引用,所以链表的存储空间相对于数组来说更大。
3.不支持直接访问:链表中的节点不能像数组一样直接访问,访问一个节点必须从头节点开始遍历,直到找到目标节点。


综上所述,链表适用于频繁进行插入和删除操作,且不需要频繁随机访问元素的场景。而在需要快速随机访问元素的情况下,数组更为合适。

3.哈希表

(1)什么是哈希?

        哈希(Hash)也称散列,是一种算法,用于将任意长度的输入映射为固定长度的输出,这个映射规则就是对应的Hash算法,而映射后的二进制串就是哈希值。

(2)哈希算法的特点

   1.哈希算法是一种单向的加密算法,无法根据哈希值反向推导出原始的数据

   2.哈希算法产生的哈希值长度固定,不论原始数据的长度如何,哈希值的长度都是固定的

   3.对于相同的输入,哈希算法始终产生相同的哈希值。即使原始数据只有微小的变化,其哈希值也会有较大的差异。

   4.对于不同的输入,哈希算法产生不同的哈希值的概率非常高,即哈希碰撞的概率非常低。

   5.哈希算法的计算速度通常较快,且不会随着原始数据的增加而显著增加。

   6.哈希算法的输出是固定长度的二进制位,可以用于唯一标识数据,验证数据的完整性和一致性。

(3)哈希表

   哈希表又称为散列表,通常由一个固定大小的数组和对应的哈希函数组成。当需要插入或查询数据时,首先将关键字(key)通过哈希函数计算得到对应的哈希值(hash value),然后将数据存储在哈希值对应的数组位置上。当需要查询数据时,也是通过哈希函数计算得到哈希值,然后直接访问对应的数组位置,从而快速地找到目标数据。

   哈希表的优势在于其快速的插入、删除和查询操作,适用于大量的数据存储和查找场景。然而,哈希表也存在一些问题,例如哈希冲突(多个关键字计算得到相同的哈希值)可能会导致插入和查询操作的效率下降。

(4)什么是哈希冲突?怎么解决

    哈希冲突指的是在哈希函数计算过程中,不同的输入却产生相同的哈希值的情况。由于哈希函数的输出空间相对输入空间要小,哈希冲突是不可避免的。

解决哈希冲突的方法有以下几种常见的策略:

1.链地址法:在哈希表的每个位置上维护一个链表,当发生哈希冲突时,将冲突的元素加入链表中。
2.开放地址法:当发生哈希冲突时,通过一定的探测方法,在哈希表中寻找下一个可用的位置存放冲突元素。
3.公共溢出区法:将所有哈希冲突的元素放入一个公共的溢出区中。
4.再哈希法:使用一个不同的哈希函数来处理哈希冲突。
 

(5)HashMap是怎么解决哈希冲突的?

      HashMap解决哈希冲突的方法是采用链地址法。当发生哈希冲突时,即不同的元素通过哈希函数被映射到相同的索引位置上,HashMap会在该索引位置的链表中存储多个元素。

4.红黑树

(1)什么是树

       树是一种非线性数据结构,它由一组节点和一组连接节点的边组成。树的节点通常表示实际对象,边表示节点之间的关系。树具有以下特点:

   1.树中有一个称为根节点的特殊节点,它没有父节点,其他节点都是它的子节点。
   2.每个节点可以有零个或多个子节点,子节点和父节点之间通过边连接。
   3.除了根节点,每个节点都有一个唯一的父节点。
   4.从根节点出发,通过边可以到达树中的任意节点,形成一棵树。
   5.树中不存在环路,即任意节点到达根节点的路径都是唯一的。

(2)什么是二叉树

       二叉树是一种特殊的树结构,其中每个节点最多有两个子节点。这两个子节点被称为左子节点和右子节点。

(3)什么是二叉搜索树

   二叉搜索树(BST)是一种特殊的二叉树结构,它满足以下条件:

   1.每个节点最多只有两个子节点,分别称为左子节点和右子节点;
   2.左子节点的值小于父节点的值,右子节点的值大于父节点的值;
   3.子树也是二叉搜索树。

(4)二叉搜索树的缺点

        二叉搜索树常用于实现各种基于搜索和排序的算法,如查找、插入、删除、中序遍历等。它的时间复杂度是O(log n),在某些特殊情况下可能会退化成链表,时间复杂度为O(n)。因此,为了保持二叉搜索树的平衡性,可以使用平衡二叉搜索树(如AVL树、红黑树)来优化性能。

(5)AVL树

    AVL树是一种自平衡二叉搜索树。它在每次插入或删除操作后,通过旋转节点来保持树的平衡性。

AVL树的特点包括:

  1. 每个节点的左子树和右子树的高度最多相差1,也就是说,树的每个节点的平衡因子(左子树高度减去右子树高度)的绝对值最多为1。
  2. 所有的节点的左子树和右子树都是AVL树。

   为了保持AVL树的平衡,当在树中进行插入或删除操作后,可能会导致某些节点的平衡被破坏。为了修复平衡,需要通过旋转节点来重新调整树的结构,使得树重新满足AVL树的性质。

(6)红黑树
    一. 介绍

     红黑树是一种自平衡的二叉搜索树。它的特点是每个节点都有一个额外的二进制值,表示节点的颜色,可以是红色或黑色。

红黑树满足以下性质:

1.每个节点要么是红色,要么是黑色。
2.根节点是黑色。
3.每个叶子节点(NIL节点,空节点)都是黑色。
4.如果一个节点是红色的,则它的两个子节点都是黑色的。
5.对于每个节点,从该节点到其子孙节点的所有路径上包含相同数目的黑色节点。(黑高)

三种基本操作:

1.变色:将某个节点的颜色从红色变为黑色,或者从黑色变为红色。

2.左旋操作:以某个节点为支点(旋转节点),将其右孩子提升为旋转节点的父节点,同时将该旋转节点作为右孩子的左孩子,并将旋转节点的右孩子的左孩子指向该旋转节点的右孩子。

3.右旋操作:以某个节点为支点(旋转节点),将其左孩子提升为该旋转节点的父节点,同时将该旋转节点作为左孩子的右孩子,并将旋转节点的左孩子的右孩子指向该旋转节点的左孩子。

      节点A为旋转中心点,节点B为其右子节点。通过左旋转操作,节点B提升为新的父节点,节点A成为节点B的左子节点,同时节点B的左子节点Y成为节点A的右子节点。

      节点A为旋转中心点,节点B为其左子节点。通过右旋转操作,节点B提升为新的父节点,节点A成为节点B的右子节点,同时节点B的右子节点Y成为节点A的左子节点。

二.查找操作

  1.从根节点开始,将要查找的值与当前节点的值进行比较。
  2.如果要查找的值等于当前节点的值,则找到了目标节点,结束查找操作。
  3.如果要查找的值小于当前节点的值,并且当前节点有左子节点,则将当前节点移动到左子节       点,并回到步骤1继续查找。
  4.如果要查找的值大于当前节点的值,并且当前节点有右子节点,则将当前节点移动到右子节点,并回到步骤1继续查找。
  5.如果要查找的值小于当前节点的值,并且当前节点没有左子节点,则要查找的值不存在于红黑树中,结束查找操作。
  6. 如果要查找的值大于当前节点的值,并且当前节点没有右子节点,则要查找的值不存在于红黑树中,结束查找操作。

   红黑树的性质保证了树的平衡性,使得树的高度维持在一个相对较小的范围内,因此红黑树的查找操作的时间复杂度为 O(log n)。

三.插入操作

    当向红黑树插入一个新节点时,需要根据红黑树的性质进行调整,以保证插入后仍然满足红黑树的五个性质。

 注意:插入的节点必须是红色,因为如果插入的节点是黑节点,那么插入的位置所在的子树黑色节点总是多1,这就破坏了红黑树的性质:对于任何一个节点,从该节点到其子孙节点的所有路径上包含相同数目的黑节点。因此,需要对红黑树进行调整来恢复平衡。如果插入的节点是红节点,在父节点(如果存在)为黑色节点时,红黑树的黑色平衡没有被破坏,不需要做自平衡操作。

场景1:红黑树为空树

       插入节点为根节点,直接将其染为黑色。(因为插入的颜色为红色,但根据红黑树性质2:根结点是黑色,所以需要变色)

场景2:插入节点的Key已经存在

  找到当前Key,直接把当前值替换成要插入的值。

场景3:插入节点的父节点为黑色

    当插入节点的父节点为黑色时,无需调整树结构,仍然满足红黑树的性质。

场景4:插入节点的父节点为红色,分五种情况

了解:父节点、祖父节点和叔叔节点

场景4.1  插入节点的父节点为红色,叔叔节点存在并且也为红色

   将父节点和叔叔节点涂为黑色,祖父节点涂为红色,以祖父节点为当前节点进行继续操作。

  变色后,祖父节点PP变成红色,如果PP的父节点是黑色,那么无需再做任何处理;若PP的父节点为红色,则违反红黑树的性质,需要将PP设置为当前节点,继续做插入操作自平衡处理,直到平衡为止。

场景4.2  插入节点的父节点为红色,叔叔节点为黑色或缺失,插入节点的父节点是其祖父节点的左子节点,插入节点是其父节点的左子节点(LL左左情况)

   1.变色:将父节点标记为黑色,将祖父节点标记为红色
   2.旋转:对祖父节点进行右旋操作


    

场景4.3  插入节点的父节点为红色,叔叔节点为黑色或缺失,插入节点的父节点是其祖父节点的左子节点,插入节点是其父节点的右子节点(LR左右情况)

  1.对父节点进行左旋操作,转化为LL情况。

  2.将父节点设置为当前节点,处理LL左左的情况

场景4.4  插入节点的父节点为红色,叔叔节点为黑色或缺失,插入节点的父节点是其祖父节点的右子节点,插入节点是其父节点的右子节点(RR右右情况)

 1.变色:将父节点标记为黑色,将祖父节点标记为红色。

 2.旋转:对祖父节点进行左旋操作


 

场景4.5  插入节点的父节点为红色,叔叔节点为黑色或缺失,插入节点的父节点是其祖父节点的右子节点,插入节点是其父节点的左子节点(RL右左情况)

  1.对父节点进行右旋操作,转化为RR情况。

  2.将父节点设置为当前节点,处理RR的情况

四.删除操作

首先要知道二叉搜索树的删除操作:分为三种情况

(1)被删节点是叶子节点,直接删除即可

(2)被删节点只有一个孩子节点,孩子节点替换被删节点

(3)被删节点有两个孩子节点

     需要找到该节点的后继节点或前驱节点来替代该节点。

    后继节点:比该节点大的最小节点,即比该节点的值大且最接近该节点值的节点;

    前驱节点:比该节点小的最大节点,即比该节点的值小且最接近该节点值的节点。

  

红黑数删除红色节点 

此时直接根据二叉搜索树删除操作删除该节点即可,不会引起红黑树性质的破坏。

红黑树删除黑色节点

U:当前要删除的节点

X:U的后继,也就是替换U的节点

Y:接替X的节点(一般是X的左孩子或右孩子,没有则为null)

如果U是叶子节点,那么X和Y都是NUll

删除的几种情况

    UXY
黑色红色黑色
黑色黑色红色
黑色黑色黑色

性质4:如果一个节点是红色的,则它的两个子节点都是黑色的

注意:不会出现X和Y都为红色,因为父子节点不会都为红色

第一种情况:X为红,Y为黑

直接X替换U,注意替换只是替换值,颜色不会替换

第二种情况:X为黑,Y为红

1.二叉搜索数删除

2.将Y变为黑色

第三种情况:X为黑,Y为黑

之后又分为4种情况

Rr第一个字母R表示Y是左孩子还是右孩子,r表示兄弟节点V是什么颜色
Rb第一个字母R表示Y是左孩子还是右孩子,r表示兄弟节点V是什么颜色
Lr第一个字母R表示Y是左孩子还是右孩子,r表示兄弟节点V是什么颜色
Lb第一个字母R表示Y是左孩子还是右孩子,r表示兄弟节点V是什么颜色

Rr和Rb,Lr和Lb操作是对称的,Rr的处理操作是先将Rr转换成Rb,然后再用Rb的方式解决。

所以先解决Rb即可。

Rb又分为3种情况

Rb0V的左右孩子都为黑色
Rb1V的左孩子为红,右孩子为红或黑
Rb2V的左孩子为黑,右孩子为红

Rb0

Rb1

Rb2

将Rb2转换为Rb1,再用Rb1的方式处理

(7)HashMap中使用红黑树而不是AVL树的原因

     AVL树和红黑树都是一种自平衡二叉搜索树, 红黑树的插入和删除操作比AVL树更高效。AVL树需要通过旋转操作来保持树的平衡,而红黑树通过颜色变换和旋转操作来实现平衡。红黑树的平衡性要求相对较宽松,因此在插入和删除操作时,红黑树需要的旋转次数较少,从而提高了性能。

5.HashMap中使用的数据结构

Java 7中,HashMap使用了一个数组(哈希表)+链表的组合来存储键值对;

Java 8中,HashMap使用了一个数组(哈希表)+链表+红黑树的组合来存储键值对

二.源码分析

1.Node结构

 //这里的Node就相当于一个桶,Node数组就相当于是一个hash table
 static class Node<K,V> implements Map.Entry<K,V> {
        final int hash;  // 哈希值
        final K key;
        V value;
        Node<K,V> next; //链表,指向下一个冲突元素

        Node(int hash, K key, V value, Node<K,V> next) {
            this.hash = hash;
            this.key = key;
            this.value = value;
            this.next = next;
        }

        public final K getKey()        { return key; }
        public final V getValue()      { return value; }
        public final String toString() { return key + "=" + value; }

        public final int hashCode() {
            return Objects.hashCode(key) ^ Objects.hashCode(value);
        }

        public final V setValue(V newValue) {
            V oldValue = value;
            value = newValue;
            return oldValue;
        }

        public final boolean equals(Object o) {
            if (o == this)
                return true;
            if (o instanceof Map.Entry) {
                Map.Entry<?,?> e = (Map.Entry<?,?>)o;
                if (Objects.equals(key, e.getKey()) &&
                        Objects.equals(value, e.getValue()))
                    return true;
            }
            return false;
        }
    }

2.属性

  //默认table大小(为2的n次幂)
    static final int DEFAULT_INITIAL_CAPACITY = 1 << 4; // aka 16

    //默认table最大长度
    static final int MAXIMUM_CAPACITY = 1 << 30;

    //默认负载因子大小
    static final float DEFAULT_LOAD_FACTOR = 0.75f;

    //树化阈值(当某个桶中的链表长度大于该值时,有可能转换成红黑树)
    static final int TREEIFY_THRESHOLD = 8;

    //树降级成为链表的阈值
    static final int UNTREEIFY_THRESHOLD = 6;

    //树化阈值(当哈希表中的所有元素个数超过64时,才会允许树化)
    //即树化条件TREEIFY_THRESHOLD和 MIN_TREEIFY_CAPACITY 都满足时才会树化
    static final int MIN_TREEIFY_CAPACITY = 64;



 // 哈希表
    transient Node<K,V>[] table;

    transient Set<Map.Entry<K,V>> entrySet;

    //当前哈希表中元素个数
    transient int size;

    //当前哈希表结构修改次数
    transient int modCount;

    //扩容阈值,当哈希表中的元素超过阈值时,触发扩容(capacity * loadFactor)
    int threshold;

    //负载因子
    final float loadFactor;

3.构造器

/**
     * 构造方法,就是做了一些校验
     * @param initialCapacity 初始容量(后面会转化为2的N次方)
     * @param loadFactor 负载因子
     */
    public HashMap(int initialCapacity, float loadFactor) {
        //initialCapacity必须是大于0,最大值也就是MAXIMUM_CAPACITY(2^30);
        if (initialCapacity < 0)
            throw new IllegalArgumentException("Illegal initial capacity: " +
                    initialCapacity);
        if (initialCapacity > MAXIMUM_CAPACITY)
            initialCapacity = MAXIMUM_CAPACITY;
        //loadFactor必须大于0
        if (loadFactor <= 0 || Float.isNaN(loadFactor))
            throw new IllegalArgumentException("Illegal load factor: " +
                    loadFactor);
        this.loadFactor = loadFactor;

        //tableSizeFor方法返回一个大于等于当前值的一个数字,并且这个数字一定是2的次方数
        this.threshold = tableSizeFor(initialCapacity);
    }


/**
     * 返回一个大于等于当前值cap的一个数字,并且这个数字一定是2的次方数
     *
     * 例 cap=10
     * n = 10 - 1 = 9
     * 0b1001 | 0b0100 => 0b1101
     * 0b1101 | 0b0011 => 0b1111
     * 0b1111 | 0b0000 => 0b1111
     * ........
     * 最后n=0b1111 => 15
     *
     * return n+1 = 16
     *
     * 总结:
     *  1.这个方法其实就是把一个二进制数从第一个1开始,把后面的数都变成1,然后最后加1得到2的次方数
     *  0001 1010 1100 =》0001 1111 1111+1 =》0010 0000 0000(2的次方数)
     *  2.为什么要右移1+2+4+8+16=31?
     *  因为int类型最大值为2^31-1
     *
     */
    static final int tableSizeFor(int cap) {
        int n = cap - 1;
        n |= n >>> 1;
        n |= n >>> 2;
        n |= n >>> 4;
        n |= n >>> 8;
        n |= n >>> 16;
        return (n < 0) ? 1 : (n >= MAXIMUM_CAPACITY) ? MAXIMUM_CAPACITY : n + 1;
    }
 public HashMap(int initialCapacity) {
        this(initialCapacity, DEFAULT_LOAD_FACTOR);
    }


    public HashMap() {
        //默认负载因子0.75
        this.loadFactor = DEFAULT_LOAD_FACTOR; // all other fields defaulted
    }


    public HashMap(Map<? extends K, ? extends V> m) {
        this.loadFactor = DEFAULT_LOAD_FACTOR;
        putMapEntries(m, false);
    }

 4.put方法

  public V put(K key, V value) {
        return putVal(hash(key), key, value, false, true);
    }
/**
     *
     * 作用:让key的hash值的高16位也参与路由寻址运算
     * 异或:相同则返回0,不同返回1
     *
     * h = 0b 0010 0010 1010 0101 1111 0011 0010 1110
     * 0b 0010 0010 1010 0101 1111 0011 0010 1110
     * ^
     * 0b 0000 0000 0000 0000 0010 0010 1010 0101
     * => 0010 0010 1010 0101 1101 0001 1000 1011
     *
     * 路由寻址算法是(table.length-1)& h ,在table长度不是很大的情况下,
     * 高16位无法参与运算,通过这个扰动函数让高16位也参与运算中来让哈希值更加散列,
     * 在后面寻址的时候,减少哈希冲突
     *
     *
     */
    static final int hash(Object key) {
        int h;
        return (key == null) ? 0 : (h = key.hashCode()) ^ (h >>> 16);
    }

  final V putVal(int hash, K key, V value, boolean onlyIfAbsent,
                   boolean evict) {
        // tab: 当前哈市Map的散列表
        // p: 当前散列表的元素
        // n:散列表数组的长度
        // i:路由寻址结果
        Node<K,V>[] tab; Node<K,V> p; int n, i;

        // 延迟初始化,第一次调用putVal时会初始化hashMap对象的散列表
        if ((tab = table) == null || (n = tab.length) == 0)
            n = (tab = resize()).length;

        //第一种情况:寻址找到的桶位正好是null,直接将key和value封装成Node放进去
        if ((p = tab[i = (n - 1) & hash]) == null)
            tab[i] = newNode(hash, key, value, null);
        else {
            //e:不为null的话,找到了一个与当前要插入的key-value一致的key的元素
            //k:表示临时的一个key
            Node<K,V> e; K k;
            //表示桶位中的元素与当前插入的元素的key完全一致,后续需要进行替换操作
            if (p.hash == hash &&
                    ((k = p.key) == key || (key != null && key.equals(k))))
                e = p;
            //红黑树的情况
            else if (p instanceof TreeNode)
                e = ((TreeNode<K,V>)p).putTreeVal(this, tab, hash, key, value);
            //链表的情况,而且链表的头元素与我们要插入的key不一致
            else {
                for (int binCount = 0; ; ++binCount) {
                    //遍历到链表的末尾也没有找到要与插入的key一致的node,需要将插入的元素放到链表的末尾
                    if ((e = p.next) == null) {
                        p.next = newNode(hash, key, value, null);
                        //如果当前链表长度达到树化标准,进行树化操作
                        if (binCount >= TREEIFY_THRESHOLD - 1) 
                            //树化操作
                            treeifyBin(tab, hash);
                        break;
                    }
                    
                    //链表中找到了相同key的node元素,需要进行替换操作
                    if (e.hash == hash &&
                            ((k = e.key) == key || (key != null && key.equals(k))))
                        break;
                    p = e;
                }
            }
            //e不等于null时,说明找到了一个与插入元素key完全一致的数据,需要进行替换
            if (e != null) { 
                V oldValue = e.value;
                if (!onlyIfAbsent || oldValue == null)
                    e.value = value;
                afterNodeAccess(e);
                return oldValue;
            }
        }
        //modCount:表示散列表结构被修改的次数(替换node元素的value不算)
        ++modCount;
        //插入新元素,size自增,如果自增后的值大于扩容阈值,则触发扩容。
        if (++size > threshold)
            resize();
        afterNodeInsertion(evict);
        return null;
    }

5.resize()扩容方法

  /**
     * 为什么需要扩容?
     * 为了解决哈希冲突导致的链化影响查询效率的问题,扩容会缓解该问题。
     * @return
     */
    final Node<K,V>[] resize() {
        //引用扩容前的哈希表
        Node<K,V>[] oldTab = table;
        //表示扩容之前table数组的长度
        int oldCap = (oldTab == null) ? 0 : oldTab.length;
        //表示扩容之前的扩容阈值,触发本次扩容的阈值
        int oldThr = threshold;
        //newCap:扩容之后table数组的大小
        //newThr:扩容之后,下次再次触发扩容的条件
        int newCap, newThr = 0;
        //oldCap > 0,说明hashmap中的散列表已经初始化过,是一次正常扩容
        if (oldCap > 0) {
            // 扩容之前的table数组大小已经达到最大阈值后,则不进行扩容且设置扩容条件为int最大值
            if (oldCap >= MAXIMUM_CAPACITY) {
                threshold = Integer.MAX_VALUE;
                return oldTab;
            }
            //oldCap左移一位,数值翻倍并且赋值给newCap;newCap小于数值最大值限制 且 扩容之前的阈值 >=16
            //则下一次扩容的阈值等于当前阈值翻倍
            else if ((newCap = oldCap << 1) < MAXIMUM_CAPACITY &&
                    oldCap >= DEFAULT_INITIAL_CAPACITY)
                newThr = oldThr << 1; // double threshold
        }
        //oldCap == 0,说明hashMap中的散列表是null
        //1.new HashMap(int initialCapacity, float loadFactor)
        //2.new HashMap(int initialCapacity)
        //3.new HashMap(map),map中有数据
        else if (oldThr > 0)
            newCap = oldThr;
        //oldCap == 0,oldThr ==0
        //new HashMap();
        else {
            newCap = DEFAULT_INITIAL_CAPACITY; //16
            newThr = (int)(DEFAULT_LOAD_FACTOR * DEFAULT_INITIAL_CAPACITY); //12
        }

        //newThr 为零时,通过newCap和loadFactor计算出一个newThr
        if (newThr == 0) {
            float ft = (float)newCap * loadFactor;
            newThr = (newCap < MAXIMUM_CAPACITY && ft < (float)MAXIMUM_CAPACITY ?
                    (int)ft : Integer.MAX_VALUE);
        }
        //把newThr赋值给threshold
        threshold = newThr;

        //创建长度为newCap的数组
        @SuppressWarnings({"rawtypes","unchecked"})
        Node<K,V>[] newTab = (Node<K,V>[])new Node[newCap];
        table = newTab;

        //本次扩容前,table不为null
        if (oldTab != null) {
            //遍历数组
            for (int j = 0; j < oldCap; ++j) {
                //当前node节点
                Node<K,V> e;
                //说明当前桶位有数据(单个数据、链表、红黑树)
                if ((e = oldTab[j]) != null) {
                    //方便JVM GC回收
                    oldTab[j] = null;

                    //第一种情况:当前桶位只有一个元素,没有发生过碰撞,直接通过寻址算法计算出
                    //当前元素存放在新数组的位置,然后放入即可。
                    if (e.next == null)
                        newTab[e.hash & (newCap - 1)] = e;
                    //第二种情况:当前节点已经树化
                    else if (e instanceof TreeNode)
                        ((TreeNode<K,V>)e).split(this, newTab, j, oldCap);
                    
                    else { // preserve order
                        //第三种情况:桶位已经形成链表,
                        //若原来数组长度为16,扩容为32
                        //若链表在原来数组索引为15的位置,那么链表中的每个Node在新数组中的位置不是索引为15,就是索引为31的位置上
                        //路由寻址算法为 hash &(table.length-1)
                        //table.length-1 由原来的  1111 变为原来的 1 1111
                        //hash值倒数第5位不确定有可能是0 1111 ,也有可能是1 1111
                        //如果是0 1111 & 1 1111 = 0 1111,就放入新数组中索引为15的位置(低位链表)
                        //如果是1 1111 & 1 1111 = 1 1111,就放入新数组中索引为31的位置(高位链表)
                        
                        //低位链表:存放在扩容之后的数组的下标位置,与当前数组的下标位置一致
                        Node<K,V> loHead = null, loTail = null;
                        //高位链表:存放在扩容之后的数组的下标位置为 当前数组下标位置 + 扩容之前数组的长度
                        Node<K,V> hiHead = null, hiTail = null;
                        Node<K,V> next;
                        do {
                            next = e.next;
                            // hash为0 1111 & 1 0000 ==0说明放入低位链表中
                            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;
    }

6.get()方法

   public V get(Object key) {
        Node<K,V> e;
        return (e = getNode(hash(key), key)) == null ? null : e.value;
    }
   final Node<K,V> getNode(int hash, Object key) {
        //tab: 引用当前hashMap的散列表
        //first:桶位中的头元素
        //e:临时node元素
        //n:table数组长度
        Node<K,V>[] tab; Node<K,V> first, e; int n; K k;
        
        //如果table不为空,并且桶位中不为空
        if ((tab = table) != null && (n = tab.length) > 0 &&
                (first = tab[(n - 1) & hash]) != null) {
            
            //第一种情况:定位出来的桶位元素 即为要get的数据,直接返回
            if (first.hash == hash && 
                    ((k = first.key) == key || (key != null && key.equals(k))))
                return first;
            
            //当前桶位中的元素不止一个,可能是 链表 或 红黑树 
            if ((e = first.next) != null) {
                
                //第二种情况:桶位升级成了红黑树
                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;
    }

7.remove()方法

   public V remove(Object key) {
        Node<K,V> e;
        return (e = removeNode(hash(key), key, null, false, true)) == null ?
                null : e.value;
    }


 @Override
    public boolean remove(Object key, Object value) {
        return removeNode(hash(key), key, value, true, true) != null;
    }
final Node<K,V> removeNode(int hash, Object key, Object value,
                               boolean matchValue, boolean movable) {

        //tab: 引用当前hashmap中的散列表
        //p:当前node元素
        //n:表示散列表数组的长度
        //index:表示寻址结果
        Node<K,V>[] tab; Node<K,V> p; int n, index;

        //table不为空并且桶位中有数据,进行查找操作并删除
        if ((tab = table) != null && (n = tab.length) > 0 &&
                (p = tab[index = (n - 1) & hash]) != null) {

            //node:查找到的结果
            //e:当前Node的下一个元素
            Node<K,V> node = null, e; K k; V v;

            //第一种情况:当前桶位中的元素即为要删除的元素
            if (p.hash == hash &&
                    ((k = p.key) == key || (key != null && key.equals(k))))
                node = p;

            //当前桶位要么是链表,要么是红黑树
            else if ((e = p.next) != null) {

                //第二种情况:当前桶位是红黑树
                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);
                }
            }

            //如果node不为空的话,说明可以按照key查找需要删除的数据了
            if (node != null && (!matchValue || (v = node.value) == value ||
                    (value != null && value.equals(v)))) {

                //第一种情况:node是树节点,需要进行树节点移除操作
                if (node instanceof TreeNode)
                    ((TreeNode<K,V>)node).removeTreeNode(this, tab, movable);
                //第二种情况:桶位元素即为查找结果,则将该元素的下一个元素放到桶位中
                else if (node == p)
                    tab[index] = node.next;
                //第三种情况:将当前元素p的下一个元素 设置成 要删除元素的 下一个元素
                else
                    p.next = node.next;
                ++modCount;
                --size;
                afterNodeRemoval(node);
                return node;
            }
        }
        return null;
    }

8.全部源码



package java.util;

import java.io.IOException;
import java.io.InvalidObjectException;
import java.io.Serializable;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.util.function.BiConsumer;
import java.util.function.BiFunction;
import java.util.function.Consumer;
import java.util.function.Function;
import sun.misc.SharedSecrets;


public class HashMap<K,V> extends AbstractMap<K,V>
        implements Map<K,V>, Cloneable, Serializable {

    private static final long serialVersionUID = 362498820763181265L;

    //默认table大小(为2的n次幂)
    static final int DEFAULT_INITIAL_CAPACITY = 1 << 4; // aka 16

    //默认table最大长度
    static final int MAXIMUM_CAPACITY = 1 << 30;

    //默认负载因子大小
    static final float DEFAULT_LOAD_FACTOR = 0.75f;

    //树化阈值(当某个桶中的链表长度大于该值时,有可能转换成红黑树)
    static final int TREEIFY_THRESHOLD = 8;

    //树降级成为链表的阈值
    static final int UNTREEIFY_THRESHOLD = 6;

    //树化阈值(当哈希表中的所有元素个数超过64时,才会允许树化)
    //即树化条件TREEIFY_THRESHOLD和 MIN_TREEIFY_CAPACITY 都满足时才会树化
    static final int MIN_TREEIFY_CAPACITY = 64;

    //这里的Node就相当于一个桶,Node数组就相当于是一个hash table
    static class Node<K,V> implements Map.Entry<K,V> {
        final int hash;  // 哈希值
        final K key;
        V value;
        Node<K,V> next; //链表,指向下一个冲突元素

        Node(int hash, K key, V value, Node<K,V> next) {
            this.hash = hash;
            this.key = key;
            this.value = value;
            this.next = next;
        }

        public final K getKey()        { return key; }
        public final V getValue()      { return value; }
        public final String toString() { return key + "=" + value; }

        public final int hashCode() {
            return Objects.hashCode(key) ^ Objects.hashCode(value);
        }

        public final V setValue(V newValue) {
            V oldValue = value;
            value = newValue;
            return oldValue;
        }

        public final boolean equals(Object o) {
            if (o == this)
                return true;
            if (o instanceof Map.Entry) {
                Map.Entry<?,?> e = (Map.Entry<?,?>)o;
                if (Objects.equals(key, e.getKey()) &&
                        Objects.equals(value, e.getValue()))
                    return true;
            }
            return false;
        }
    }


    /**
     *
     * 作用:让key的hash值的高16位也参与路由寻址运算
     * 异或:相同则返回0,不同返回1
     *
     * h = 0b 0010 0010 1010 0101 1111 0011 0010 1110
     * 0b 0010 0010 1010 0101 1111 0011 0010 1110
     * ^
     * 0b 0000 0000 0000 0000 0010 0010 1010 0101
     * => 0010 0010 1010 0101 1101 0001 1000 1011
     *
     * 路由寻址算法是(table.length-1)& h ,在table长度不是很大的情况下,
     * 高16位无法参与运算,通过这个扰动函数让高16位也参与运算中来让哈希值更加散列,
     * 在后面寻址的时候,减少哈希冲突
     *
     *
     */
    static final int hash(Object key) {
        int h;
        return (key == null) ? 0 : (h = key.hashCode()) ^ (h >>> 16);
    }


    static Class<?> comparableClassFor(Object x) {
        if (x instanceof Comparable) {
            Class<?> c; Type[] ts, as; Type t; ParameterizedType p;
            if ((c = x.getClass()) == String.class) // bypass checks
                return c;
            if ((ts = c.getGenericInterfaces()) != null) {
                for (int i = 0; i < ts.length; ++i) {
                    if (((t = ts[i]) instanceof ParameterizedType) &&
                            ((p = (ParameterizedType)t).getRawType() ==
                                    Comparable.class) &&
                            (as = p.getActualTypeArguments()) != null &&
                            as.length == 1 && as[0] == c) // type arg is c
                        return c;
                }
            }
        }
        return null;
    }


    @SuppressWarnings({"rawtypes","unchecked"}) // for cast to Comparable
    static int compareComparables(Class<?> kc, Object k, Object x) {
        return (x == null || x.getClass() != kc ? 0 :
                ((Comparable)k).compareTo(x));
    }

    /**
     * 返回一个大于等于当前值cap的一个数字,并且这个数字一定是2的次方数
     *
     * 例 cap=10
     * n = 10 - 1 = 9
     * 0b1001 | 0b0100 => 0b1101
     * 0b1101 | 0b0011 => 0b1111
     * 0b1111 | 0b0000 => 0b1111
     * ........
     * 最后n=0b1111 => 15
     *
     * return n+1 = 16
     *
     * 总结:
     *  1.这个方法其实就是把一个二进制数从第一个1开始,把后面的数都变成1,然后最后加1得到2的次方数
     *  0001 1010 1100 =》0001 1111 1111+1 =》0010 0000 0000(2的次方数)
     *  2.为什么要右移1+2+4+8+16=31?
     *  因为int类型最大值为2^31-1
     *
     */
    static final int tableSizeFor(int cap) {
        int n = cap - 1;
        n |= n >>> 1;
        n |= n >>> 2;
        n |= n >>> 4;
        n |= n >>> 8;
        n |= n >>> 16;
        return (n < 0) ? 1 : (n >= MAXIMUM_CAPACITY) ? MAXIMUM_CAPACITY : n + 1;
    }

    /* ---------------- Fields -------------- */

    // 哈希表
    transient Node<K,V>[] table;


    transient Set<Map.Entry<K,V>> entrySet;

    //当前哈希表中元素个数
    transient int size;

    //当前哈希表结构修改次数
    transient int modCount;

    //扩容阈值,当哈希表中的元素超过阈值时,触发扩容(capacity * loadFactor)
    int threshold;

    //负载因子
    final float loadFactor;

    /* ---------------- Public operations -------------- */


    /**
     * 构造方法,就是做了一些校验
     * @param initialCapacity 初始容量(2的N次幂)
     * @param loadFactor 负载因子
     */
    public HashMap(int initialCapacity, float loadFactor) {
        //initialCapacity必须是大于0,最大值也就是MAXIMUM_CAPACITY(2^30);
        if (initialCapacity < 0)
            throw new IllegalArgumentException("Illegal initial capacity: " +
                    initialCapacity);
        if (initialCapacity > MAXIMUM_CAPACITY)
            initialCapacity = MAXIMUM_CAPACITY;
        //loadFactor必须大于0
        if (loadFactor <= 0 || Float.isNaN(loadFactor))
            throw new IllegalArgumentException("Illegal load factor: " +
                    loadFactor);
        this.loadFactor = loadFactor;

        //tableSizeFor方法返回一个大于等于当前值的一个数字,并且这个数字一定是2的次方数
        this.threshold = tableSizeFor(initialCapacity);
    }


    public HashMap(int initialCapacity) {
        this(initialCapacity, DEFAULT_LOAD_FACTOR);
    }


    public HashMap() {
        //默认负载因子0.75
        this.loadFactor = DEFAULT_LOAD_FACTOR; // all other fields defaulted
    }


    public HashMap(Map<? extends K, ? extends V> m) {
        this.loadFactor = DEFAULT_LOAD_FACTOR;
        putMapEntries(m, false);
    }


    final void putMapEntries(Map<? extends K, ? extends V> m, boolean evict) {
        int s = m.size();
        if (s > 0) {
            if (table == null) { // pre-size
                float ft = ((float)s / loadFactor) + 1.0F;
                int t = ((ft < (float)MAXIMUM_CAPACITY) ?
                        (int)ft : MAXIMUM_CAPACITY);
                if (t > threshold)
                    threshold = tableSizeFor(t);
            }
            else if (s > threshold)
                resize();
            for (Map.Entry<? extends K, ? extends V> e : m.entrySet()) {
                K key = e.getKey();
                V value = e.getValue();
                putVal(hash(key), key, value, false, evict);
            }
        }
    }


    public int size() {
        return size;
    }

    public boolean isEmpty() {
        return size == 0;
    }


    public V get(Object key) {
        Node<K,V> e;
        return (e = getNode(hash(key), key)) == null ? null : e.value;
    }


    final Node<K,V> getNode(int hash, Object key) {
        //tab: 引用当前hashMap的散列表
        //first:桶位中的头元素
        //e:临时node元素
        //n:table数组长度
        Node<K,V>[] tab; Node<K,V> first, e; int n; K k;

        //如果table不为空,并且桶位中不为空
        if ((tab = table) != null && (n = tab.length) > 0 &&
                (first = tab[(n - 1) & hash]) != null) {

            //第一种情况:定位出来的桶位元素 即为要get的数据,直接返回
            if (first.hash == hash &&
                    ((k = first.key) == key || (key != null && key.equals(k))))
                return first;

            //当前桶位中的元素不止一个,可能是 链表 或 红黑树
            if ((e = first.next) != null) {

                //第二种情况:桶位升级成了红黑树
                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;
    }


    public boolean containsKey(Object key) {
        return getNode(hash(key), key) != null;
    }


    public V put(K key, V value) {
        return putVal(hash(key), key, value, false, true);
    }


    final V putVal(int hash, K key, V value, boolean onlyIfAbsent,
                   boolean evict) {
        // tab: 当前哈市Map的散列表
        // p: 当前散列表的元素
        // n:散列表数组的长度
        // i:路由寻址结果
        Node<K,V>[] tab; Node<K,V> p; int n, i;

        // 延迟初始化,第一次调用putVal时会初始化hashMap对象的散列表
        if ((tab = table) == null || (n = tab.length) == 0)
            n = (tab = resize()).length;

        //第一种情况:寻址找到的桶位正好是null,直接将key和value封装成Node放进去
        if ((p = tab[i = (n - 1) & hash]) == null)
            tab[i] = newNode(hash, key, value, null);
        else {
            //e:不为null的话,找到了一个与当前要插入的key-value一致的key的元素
            //k:表示临时的一个key
            Node<K,V> e; K k;
            //表示桶位中的元素与当前插入的元素的key完全一致,后续需要进行替换操作
            if (p.hash == hash &&
                    ((k = p.key) == key || (key != null && key.equals(k))))
                e = p;
            //红黑树的情况
            else if (p instanceof TreeNode)
                e = ((TreeNode<K,V>)p).putTreeVal(this, tab, hash, key, value);
            //链表的情况,而且链表的头元素与我们要插入的key不一致
            else {
                for (int binCount = 0; ; ++binCount) {
                    //遍历到链表的末尾也没有找到要与插入的key一致的node,需要将插入的元素放到链表的末尾
                    if ((e = p.next) == null) {
                        p.next = newNode(hash, key, value, null);
                        //如果当前链表长度达到树化标准,进行树化操作
                        if (binCount >= TREEIFY_THRESHOLD - 1)
                            //树化操作
                            treeifyBin(tab, hash);
                        break;
                    }

                    //链表中找到了相同key的node元素,需要进行替换操作
                    if (e.hash == hash &&
                            ((k = e.key) == key || (key != null && key.equals(k))))
                        break;
                    p = e;
                }
            }
            //e不等于null时,说明找到了一个与插入元素key完全一致的数据,需要进行替换
            if (e != null) {
                V oldValue = e.value;
                if (!onlyIfAbsent || oldValue == null)
                    e.value = value;
                afterNodeAccess(e);
                return oldValue;
            }
        }
        //modCount:表示散列表结构被修改的次数(替换node元素的value不算)
        ++modCount;
        //插入新元素,size自增,如果自增后的值大于扩容阈值,则触发扩容。
        if (++size > threshold)
            resize();
        afterNodeInsertion(evict);
        return null;
    }

    /**
     * 为什么需要扩容?
     * 为了解决哈希冲突导致的链化影响查询效率的问题,扩容会缓解该问题。
     * @return
     */
    final Node<K,V>[] resize() {
        //引用扩容前的哈希表
        Node<K,V>[] oldTab = table;
        //表示扩容之前table数组的长度
        int oldCap = (oldTab == null) ? 0 : oldTab.length;
        //表示扩容之前的扩容阈值,触发本次扩容的阈值
        int oldThr = threshold;
        //newCap:扩容之后table数组的大小
        //newThr:扩容之后,下次再次触发扩容的条件
        int newCap, newThr = 0;
        //oldCap > 0,说明hashmap中的散列表已经初始化过,是一次正常扩容
        if (oldCap > 0) {
            // 扩容之前的table数组大小已经达到最大阈值后,则不进行扩容且设置扩容条件为int最大值
            if (oldCap >= MAXIMUM_CAPACITY) {
                threshold = Integer.MAX_VALUE;
                return oldTab;
            }
            //oldCap左移一位,数值翻倍并且赋值给newCap;newCap小于数值最大值限制 且 扩容之前的阈值 >=16
            //则下一次扩容的阈值等于当前阈值翻倍
            else if ((newCap = oldCap << 1) < MAXIMUM_CAPACITY &&
                    oldCap >= DEFAULT_INITIAL_CAPACITY)
                newThr = oldThr << 1; // double threshold
        }
        //oldCap == 0,说明hashMap中的散列表是null
        //1.new HashMap(int initialCapacity, float loadFactor)
        //2.new HashMap(int initialCapacity)
        //3.new HashMap(map),map中有数据
        else if (oldThr > 0)
            newCap = oldThr;
        //oldCap == 0,oldThr ==0
        //new HashMap();
        else {
            newCap = DEFAULT_INITIAL_CAPACITY; //16
            newThr = (int)(DEFAULT_LOAD_FACTOR * DEFAULT_INITIAL_CAPACITY); //12
        }

        //newThr 为零时,通过newCap和loadFactor计算出一个newThr
        if (newThr == 0) {
            float ft = (float)newCap * loadFactor;
            newThr = (newCap < MAXIMUM_CAPACITY && ft < (float)MAXIMUM_CAPACITY ?
                    (int)ft : Integer.MAX_VALUE);
        }
        //把newThr赋值给threshold
        threshold = newThr;

        //创建长度为newCap的数组
        @SuppressWarnings({"rawtypes","unchecked"})
        Node<K,V>[] newTab = (Node<K,V>[])new Node[newCap];
        table = newTab;

        //本次扩容前,table不为null
        if (oldTab != null) {
            //遍历数组
            for (int j = 0; j < oldCap; ++j) {
                //当前node节点
                Node<K,V> e;
                //说明当前桶位有数据(单个数据、链表、红黑树)
                if ((e = oldTab[j]) != null) {
                    //方便JVM GC回收
                    oldTab[j] = null;

                    //第一种情况:当前桶位只有一个元素,没有发生过碰撞,直接通过寻址算法计算出
                    //当前元素存放在新数组的位置,然后放入即可。
                    if (e.next == null)
                        newTab[e.hash & (newCap - 1)] = e;
                    //第二种情况:当前节点已经树化
                    else if (e instanceof TreeNode)
                        ((TreeNode<K,V>)e).split(this, newTab, j, oldCap);

                    else { // preserve order
                        //第三种情况:桶位已经形成链表,
                        //若原来数组长度为16,扩容为32
                        //若链表在原来数组索引为15的位置,那么链表中的每个Node在新数组中的位置不是索引为15,就是索引为31的位置上
                        //路由寻址算法为 hash &(table.length-1)
                        //table.length-1 由原来的  1111 变为原来的 1 1111
                        //hash值倒数第5位不确定有可能是0 1111 ,也有可能是1 1111
                        //如果是0 1111 & 1 1111 = 0 1111,就放入新数组中索引为15的位置(低位链表)
                        //如果是1 1111 & 1 1111 = 1 1111,就放入新数组中索引为31的位置(高位链表)

                        //低位链表:存放在扩容之后的数组的下标位置,与当前数组的下标位置一致
                        Node<K,V> loHead = null, loTail = null;
                        //高位链表:存放在扩容之后的数组的下标位置为 当前数组下标位置 + 扩容之前数组的长度
                        Node<K,V> hiHead = null, hiTail = null;
                        Node<K,V> next;
                        do {
                            next = e.next;
                            // hash为0 1111 & 1 0000 ==0说明放入低位链表中
                            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;
    }


    final void treeifyBin(Node<K,V>[] tab, int hash) {
        int n, index; Node<K,V> e;
        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);
            if ((tab[index] = hd) != null)
                hd.treeify(tab);
        }
    }


    public void putAll(Map<? extends K, ? extends V> m) {
        putMapEntries(m, true);
    }

    public V remove(Object key) {
        Node<K,V> e;
        return (e = removeNode(hash(key), key, null, false, true)) == null ?
                null : e.value;
    }


    final Node<K,V> removeNode(int hash, Object key, Object value,
                               boolean matchValue, boolean movable) {

        //tab: 引用当前hashmap中的散列表
        //p:当前node元素
        //n:表示散列表数组的长度
        //index:表示寻址结果
        Node<K,V>[] tab; Node<K,V> p; int n, index;

        //table不为空并且桶位中有数据,进行查找操作并删除
        if ((tab = table) != null && (n = tab.length) > 0 &&
                (p = tab[index = (n - 1) & hash]) != null) {

            //node:查找到的结果
            //e:当前Node的下一个元素
            Node<K,V> node = null, e; K k; V v;

            //第一种情况:当前桶位中的元素即为要删除的元素
            if (p.hash == hash &&
                    ((k = p.key) == key || (key != null && key.equals(k))))
                node = p;

            //当前桶位要么是链表,要么是红黑树
            else if ((e = p.next) != null) {

                //第二种情况:当前桶位是红黑树
                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);
                }
            }

            //如果node不为空的话,说明可以按照key查找需要删除的数据了
            if (node != null && (!matchValue || (v = node.value) == value ||
                    (value != null && value.equals(v)))) {

                //第一种情况:node是树节点,需要进行树节点移除操作
                if (node instanceof TreeNode)
                    ((TreeNode<K,V>)node).removeTreeNode(this, tab, movable);
                //第二种情况:桶位元素即为查找结果,则将该元素的下一个元素放到桶位中
                else if (node == p)
                    tab[index] = node.next;
                //第三种情况:将当前元素p的下一个元素 设置成 要删除元素的 下一个元素
                else
                    p.next = node.next;
                ++modCount;
                --size;
                afterNodeRemoval(node);
                return node;
            }
        }
        return null;
    }


    public void clear() {
        Node<K,V>[] tab;
        modCount++;
        if ((tab = table) != null && size > 0) {
            size = 0;
            for (int i = 0; i < tab.length; ++i)
                tab[i] = null;
        }
    }


    public boolean containsValue(Object value) {
        Node<K,V>[] tab; V v;
        if ((tab = table) != null && size > 0) {
            for (int i = 0; i < tab.length; ++i) {
                for (Node<K,V> e = tab[i]; e != null; e = e.next) {
                    if ((v = e.value) == value ||
                            (value != null && value.equals(v)))
                        return true;
                }
            }
        }
        return false;
    }


    public Set<K> keySet() {
        Set<K> ks = keySet;
        if (ks == null) {
            ks = new KeySet();
            keySet = ks;
        }
        return ks;
    }

    final class KeySet extends AbstractSet<K> {
        public final int size()                 { return size; }
        public final void clear()               { HashMap.this.clear(); }
        public final Iterator<K> iterator()     { return new KeyIterator(); }
        public final boolean contains(Object o) { return containsKey(o); }
        public final boolean remove(Object key) {
            return removeNode(hash(key), key, null, false, true) != null;
        }
        public final Spliterator<K> spliterator() {
            return new KeySpliterator<>(HashMap.this, 0, -1, 0, 0);
        }
        public final void forEach(Consumer<? super K> action) {
            Node<K,V>[] tab;
            if (action == null)
                throw new NullPointerException();
            if (size > 0 && (tab = table) != null) {
                int mc = modCount;
                for (int i = 0; i < tab.length; ++i) {
                    for (Node<K,V> e = tab[i]; e != null; e = e.next)
                        action.accept(e.key);
                }
                if (modCount != mc)
                    throw new ConcurrentModificationException();
            }
        }
    }


    public Collection<V> values() {
        Collection<V> vs = values;
        if (vs == null) {
            vs = new Values();
            values = vs;
        }
        return vs;
    }

    final class Values extends AbstractCollection<V> {
        public final int size()                 { return size; }
        public final void clear()               { HashMap.this.clear(); }
        public final Iterator<V> iterator()     { return new ValueIterator(); }
        public final boolean contains(Object o) { return containsValue(o); }
        public final Spliterator<V> spliterator() {
            return new ValueSpliterator<>(HashMap.this, 0, -1, 0, 0);
        }
        public final void forEach(Consumer<? super V> action) {
            Node<K,V>[] tab;
            if (action == null)
                throw new NullPointerException();
            if (size > 0 && (tab = table) != null) {
                int mc = modCount;
                for (int i = 0; i < tab.length; ++i) {
                    for (Node<K,V> e = tab[i]; e != null; e = e.next)
                        action.accept(e.value);
                }
                if (modCount != mc)
                    throw new ConcurrentModificationException();
            }
        }
    }


    public Set<Map.Entry<K,V>> entrySet() {
        Set<Map.Entry<K,V>> es;
        return (es = entrySet) == null ? (entrySet = new EntrySet()) : es;
    }

    final class EntrySet extends AbstractSet<Map.Entry<K,V>> {
        public final int size()                 { return size; }
        public final void clear()               { HashMap.this.clear(); }
        public final Iterator<Map.Entry<K,V>> iterator() {
            return new EntryIterator();
        }
        public final boolean contains(Object o) {
            if (!(o instanceof Map.Entry))
                return false;
            Map.Entry<?,?> e = (Map.Entry<?,?>) o;
            Object key = e.getKey();
            Node<K,V> candidate = getNode(hash(key), key);
            return candidate != null && candidate.equals(e);
        }
        public final boolean remove(Object o) {
            if (o instanceof Map.Entry) {
                Map.Entry<?,?> e = (Map.Entry<?,?>) o;
                Object key = e.getKey();
                Object value = e.getValue();
                return removeNode(hash(key), key, value, true, true) != null;
            }
            return false;
        }
        public final Spliterator<Map.Entry<K,V>> spliterator() {
            return new EntrySpliterator<>(HashMap.this, 0, -1, 0, 0);
        }
        public final void forEach(Consumer<? super Map.Entry<K,V>> action) {
            Node<K,V>[] tab;
            if (action == null)
                throw new NullPointerException();
            if (size > 0 && (tab = table) != null) {
                int mc = modCount;
                for (int i = 0; i < tab.length; ++i) {
                    for (Node<K,V> e = tab[i]; e != null; e = e.next)
                        action.accept(e);
                }
                if (modCount != mc)
                    throw new ConcurrentModificationException();
            }
        }
    }

    // Overrides of JDK8 Map extension methods

    @Override
    public V getOrDefault(Object key, V defaultValue) {
        Node<K,V> e;
        return (e = getNode(hash(key), key)) == null ? defaultValue : e.value;
    }

    @Override
    public V putIfAbsent(K key, V value) {
        return putVal(hash(key), key, value, true, true);
    }

    @Override
    public boolean remove(Object key, Object value) {
        return removeNode(hash(key), key, value, true, true) != null;
    }

    @Override
    public boolean replace(K key, V oldValue, V newValue) {
        Node<K,V> e; V v;
        if ((e = getNode(hash(key), key)) != null &&
                ((v = e.value) == oldValue || (v != null && v.equals(oldValue)))) {
            e.value = newValue;
            afterNodeAccess(e);
            return true;
        }
        return false;
    }

    @Override
    public V replace(K key, V value) {
        Node<K,V> e;
        if ((e = getNode(hash(key), key)) != null) {
            V oldValue = e.value;
            e.value = value;
            afterNodeAccess(e);
            return oldValue;
        }
        return null;
    }

    @Override
    public V computeIfAbsent(K key,
                             Function<? super K, ? extends V> mappingFunction) {
        if (mappingFunction == null)
            throw new NullPointerException();
        int hash = hash(key);
        Node<K,V>[] tab; Node<K,V> first; int n, i;
        int binCount = 0;
        TreeNode<K,V> t = null;
        Node<K,V> old = null;
        if (size > threshold || (tab = table) == null ||
                (n = tab.length) == 0)
            n = (tab = resize()).length;
        if ((first = tab[i = (n - 1) & hash]) != null) {
            if (first instanceof TreeNode)
                old = (t = (TreeNode<K,V>)first).getTreeNode(hash, key);
            else {
                Node<K,V> e = first; K k;
                do {
                    if (e.hash == hash &&
                            ((k = e.key) == key || (key != null && key.equals(k)))) {
                        old = e;
                        break;
                    }
                    ++binCount;
                } while ((e = e.next) != null);
            }
            V oldValue;
            if (old != null && (oldValue = old.value) != null) {
                afterNodeAccess(old);
                return oldValue;
            }
        }
        V v = mappingFunction.apply(key);
        if (v == null) {
            return null;
        } else if (old != null) {
            old.value = v;
            afterNodeAccess(old);
            return v;
        }
        else if (t != null)
            t.putTreeVal(this, tab, hash, key, v);
        else {
            tab[i] = newNode(hash, key, v, first);
            if (binCount >= TREEIFY_THRESHOLD - 1)
                treeifyBin(tab, hash);
        }
        ++modCount;
        ++size;
        afterNodeInsertion(true);
        return v;
    }

    public V computeIfPresent(K key,
                              BiFunction<? super K, ? super V, ? extends V> remappingFunction) {
        if (remappingFunction == null)
            throw new NullPointerException();
        Node<K,V> e; V oldValue;
        int hash = hash(key);
        if ((e = getNode(hash, key)) != null &&
                (oldValue = e.value) != null) {
            V v = remappingFunction.apply(key, oldValue);
            if (v != null) {
                e.value = v;
                afterNodeAccess(e);
                return v;
            }
            else
                removeNode(hash, key, null, false, true);
        }
        return null;
    }

    @Override
    public V compute(K key,
                     BiFunction<? super K, ? super V, ? extends V> remappingFunction) {
        if (remappingFunction == null)
            throw new NullPointerException();
        int hash = hash(key);
        Node<K,V>[] tab; Node<K,V> first; int n, i;
        int binCount = 0;
        TreeNode<K,V> t = null;
        Node<K,V> old = null;
        if (size > threshold || (tab = table) == null ||
                (n = tab.length) == 0)
            n = (tab = resize()).length;
        if ((first = tab[i = (n - 1) & hash]) != null) {
            if (first instanceof TreeNode)
                old = (t = (TreeNode<K,V>)first).getTreeNode(hash, key);
            else {
                Node<K,V> e = first; K k;
                do {
                    if (e.hash == hash &&
                            ((k = e.key) == key || (key != null && key.equals(k)))) {
                        old = e;
                        break;
                    }
                    ++binCount;
                } while ((e = e.next) != null);
            }
        }
        V oldValue = (old == null) ? null : old.value;
        V v = remappingFunction.apply(key, oldValue);
        if (old != null) {
            if (v != null) {
                old.value = v;
                afterNodeAccess(old);
            }
            else
                removeNode(hash, key, null, false, true);
        }
        else if (v != null) {
            if (t != null)
                t.putTreeVal(this, tab, hash, key, v);
            else {
                tab[i] = newNode(hash, key, v, first);
                if (binCount >= TREEIFY_THRESHOLD - 1)
                    treeifyBin(tab, hash);
            }
            ++modCount;
            ++size;
            afterNodeInsertion(true);
        }
        return v;
    }

    @Override
    public V merge(K key, V value,
                   BiFunction<? super V, ? super V, ? extends V> remappingFunction) {
        if (value == null)
            throw new NullPointerException();
        if (remappingFunction == null)
            throw new NullPointerException();
        int hash = hash(key);
        Node<K,V>[] tab; Node<K,V> first; int n, i;
        int binCount = 0;
        TreeNode<K,V> t = null;
        Node<K,V> old = null;
        if (size > threshold || (tab = table) == null ||
                (n = tab.length) == 0)
            n = (tab = resize()).length;
        if ((first = tab[i = (n - 1) & hash]) != null) {
            if (first instanceof TreeNode)
                old = (t = (TreeNode<K,V>)first).getTreeNode(hash, key);
            else {
                Node<K,V> e = first; K k;
                do {
                    if (e.hash == hash &&
                            ((k = e.key) == key || (key != null && key.equals(k)))) {
                        old = e;
                        break;
                    }
                    ++binCount;
                } while ((e = e.next) != null);
            }
        }
        if (old != null) {
            V v;
            if (old.value != null)
                v = remappingFunction.apply(old.value, value);
            else
                v = value;
            if (v != null) {
                old.value = v;
                afterNodeAccess(old);
            }
            else
                removeNode(hash, key, null, false, true);
            return v;
        }
        if (value != null) {
            if (t != null)
                t.putTreeVal(this, tab, hash, key, value);
            else {
                tab[i] = newNode(hash, key, value, first);
                if (binCount >= TREEIFY_THRESHOLD - 1)
                    treeifyBin(tab, hash);
            }
            ++modCount;
            ++size;
            afterNodeInsertion(true);
        }
        return value;
    }

    @Override
    public void forEach(BiConsumer<? super K, ? super V> action) {
        Node<K,V>[] tab;
        if (action == null)
            throw new NullPointerException();
        if (size > 0 && (tab = table) != null) {
            int mc = modCount;
            for (int i = 0; i < tab.length; ++i) {
                for (Node<K,V> e = tab[i]; e != null; e = e.next)
                    action.accept(e.key, e.value);
            }
            if (modCount != mc)
                throw new ConcurrentModificationException();
        }
    }

    @Override
    public void replaceAll(BiFunction<? super K, ? super V, ? extends V> function) {
        Node<K,V>[] tab;
        if (function == null)
            throw new NullPointerException();
        if (size > 0 && (tab = table) != null) {
            int mc = modCount;
            for (int i = 0; i < tab.length; ++i) {
                for (Node<K,V> e = tab[i]; e != null; e = e.next) {
                    e.value = function.apply(e.key, e.value);
                }
            }
            if (modCount != mc)
                throw new ConcurrentModificationException();
        }
    }

    /* ------------------------------------------------------------ */
    // Cloning and serialization

    /**
     * Returns a shallow copy of this <tt>HashMap</tt> instance: the keys and
     * values themselves are not cloned.
     *
     * @return a shallow copy of this map
     */
    @SuppressWarnings("unchecked")
    @Override
    public Object clone() {
        HashMap<K,V> result;
        try {
            result = (HashMap<K,V>)super.clone();
        } catch (CloneNotSupportedException e) {
            // this shouldn't happen, since we are Cloneable
            throw new InternalError(e);
        }
        result.reinitialize();
        result.putMapEntries(this, false);
        return result;
    }

    // These methods are also used when serializing HashSets
    final float loadFactor() { return loadFactor; }
    final int capacity() {
        return (table != null) ? table.length :
                (threshold > 0) ? threshold :
                        DEFAULT_INITIAL_CAPACITY;
    }

    /**
     * Save the state of the <tt>HashMap</tt> instance to a stream (i.e.,
     * serialize it).
     *
     * @serialData The <i>capacity</i> of the HashMap (the length of the
     *             bucket array) is emitted (int), followed by the
     *             <i>size</i> (an int, the number of key-value
     *             mappings), followed by the key (Object) and value (Object)
     *             for each key-value mapping.  The key-value mappings are
     *             emitted in no particular order.
     */
    private void writeObject(java.io.ObjectOutputStream s)
            throws IOException {
        int buckets = capacity();
        // Write out the threshold, loadfactor, and any hidden stuff
        s.defaultWriteObject();
        s.writeInt(buckets);
        s.writeInt(size);
        internalWriteEntries(s);
    }

    /**
     * Reconstitutes this map from a stream (that is, deserializes it).
     * @param s the stream
     * @throws ClassNotFoundException if the class of a serialized object
     *         could not be found
     * @throws IOException if an I/O error occurs
     */
    private void readObject(java.io.ObjectInputStream s)
            throws IOException, ClassNotFoundException {
        // Read in the threshold (ignored), loadfactor, and any hidden stuff
        s.defaultReadObject();
        reinitialize();
        if (loadFactor <= 0 || Float.isNaN(loadFactor))
            throw new InvalidObjectException("Illegal load factor: " +
                    loadFactor);
        s.readInt();                // Read and ignore number of buckets
        int mappings = s.readInt(); // Read number of mappings (size)
        if (mappings < 0)
            throw new InvalidObjectException("Illegal mappings count: " +
                    mappings);
        else if (mappings > 0) { // (if zero, use defaults)
            // Size the table using given load factor only if within
            // range of 0.25...4.0
            float lf = Math.min(Math.max(0.25f, loadFactor), 4.0f);
            float fc = (float)mappings / lf + 1.0f;
            int cap = ((fc < DEFAULT_INITIAL_CAPACITY) ?
                    DEFAULT_INITIAL_CAPACITY :
                    (fc >= MAXIMUM_CAPACITY) ?
                            MAXIMUM_CAPACITY :
                            tableSizeFor((int)fc));
            float ft = (float)cap * lf;
            threshold = ((cap < MAXIMUM_CAPACITY && ft < MAXIMUM_CAPACITY) ?
                    (int)ft : Integer.MAX_VALUE);

            // Check Map.Entry[].class since it's the nearest public type to
            // what we're actually creating.
            SharedSecrets.getJavaOISAccess().checkArray(s, Map.Entry[].class, cap);
            @SuppressWarnings({"rawtypes","unchecked"})
            Node<K,V>[] tab = (Node<K,V>[])new Node[cap];
            table = tab;

            // Read the keys and values, and put the mappings in the HashMap
            for (int i = 0; i < mappings; i++) {
                @SuppressWarnings("unchecked")
                K key = (K) s.readObject();
                @SuppressWarnings("unchecked")
                V value = (V) s.readObject();
                putVal(hash(key), key, value, false, false);
            }
        }
    }

    /* ------------------------------------------------------------ */
    // iterators

    abstract class HashIterator {
        Node<K,V> next;        // next entry to return
        Node<K,V> current;     // current entry
        int expectedModCount;  // for fast-fail
        int index;             // current slot

        HashIterator() {
            expectedModCount = modCount;
            Node<K,V>[] t = table;
            current = next = null;
            index = 0;
            if (t != null && size > 0) { // advance to first entry
                do {} while (index < t.length && (next = t[index++]) == null);
            }
        }

        public final boolean hasNext() {
            return next != null;
        }

        final Node<K,V> nextNode() {
            Node<K,V>[] t;
            Node<K,V> e = next;
            if (modCount != expectedModCount)
                throw new ConcurrentModificationException();
            if (e == null)
                throw new NoSuchElementException();
            if ((next = (current = e).next) == null && (t = table) != null) {
                do {} while (index < t.length && (next = t[index++]) == null);
            }
            return e;
        }

        public final void remove() {
            Node<K,V> p = current;
            if (p == null)
                throw new IllegalStateException();
            if (modCount != expectedModCount)
                throw new ConcurrentModificationException();
            current = null;
            K key = p.key;
            removeNode(hash(key), key, null, false, false);
            expectedModCount = modCount;
        }
    }

    final class KeyIterator extends HashIterator
            implements Iterator<K> {
        public final K next() { return nextNode().key; }
    }

    final class ValueIterator extends HashIterator
            implements Iterator<V> {
        public final V next() { return nextNode().value; }
    }

    final class EntryIterator extends HashIterator
            implements Iterator<Map.Entry<K,V>> {
        public final Map.Entry<K,V> next() { return nextNode(); }
    }

    /* ------------------------------------------------------------ */
    // spliterators

    static class HashMapSpliterator<K,V> {
        final HashMap<K,V> map;
        Node<K,V> current;          // current node
        int index;                  // current index, modified on advance/split
        int fence;                  // one past last index
        int est;                    // size estimate
        int expectedModCount;       // for comodification checks

        HashMapSpliterator(HashMap<K,V> m, int origin,
                           int fence, int est,
                           int expectedModCount) {
            this.map = m;
            this.index = origin;
            this.fence = fence;
            this.est = est;
            this.expectedModCount = expectedModCount;
        }

        final int getFence() { // initialize fence and size on first use
            int hi;
            if ((hi = fence) < 0) {
                HashMap<K,V> m = map;
                est = m.size;
                expectedModCount = m.modCount;
                Node<K,V>[] tab = m.table;
                hi = fence = (tab == null) ? 0 : tab.length;
            }
            return hi;
        }

        public final long estimateSize() {
            getFence(); // force init
            return (long) est;
        }
    }

    static final class KeySpliterator<K,V>
            extends HashMapSpliterator<K,V>
            implements Spliterator<K> {
        KeySpliterator(HashMap<K,V> m, int origin, int fence, int est,
                       int expectedModCount) {
            super(m, origin, fence, est, expectedModCount);
        }

        public KeySpliterator<K,V> trySplit() {
            int hi = getFence(), lo = index, mid = (lo + hi) >>> 1;
            return (lo >= mid || current != null) ? null :
                    new KeySpliterator<>(map, lo, index = mid, est >>>= 1,
                            expectedModCount);
        }

        public void forEachRemaining(Consumer<? super K> action) {
            int i, hi, mc;
            if (action == null)
                throw new NullPointerException();
            HashMap<K,V> m = map;
            Node<K,V>[] tab = m.table;
            if ((hi = fence) < 0) {
                mc = expectedModCount = m.modCount;
                hi = fence = (tab == null) ? 0 : tab.length;
            }
            else
                mc = expectedModCount;
            if (tab != null && tab.length >= hi &&
                    (i = index) >= 0 && (i < (index = hi) || current != null)) {
                Node<K,V> p = current;
                current = null;
                do {
                    if (p == null)
                        p = tab[i++];
                    else {
                        action.accept(p.key);
                        p = p.next;
                    }
                } while (p != null || i < hi);
                if (m.modCount != mc)
                    throw new ConcurrentModificationException();
            }
        }

        public boolean tryAdvance(Consumer<? super K> action) {
            int hi;
            if (action == null)
                throw new NullPointerException();
            Node<K,V>[] tab = map.table;
            if (tab != null && tab.length >= (hi = getFence()) && index >= 0) {
                while (current != null || index < hi) {
                    if (current == null)
                        current = tab[index++];
                    else {
                        K k = current.key;
                        current = current.next;
                        action.accept(k);
                        if (map.modCount != expectedModCount)
                            throw new ConcurrentModificationException();
                        return true;
                    }
                }
            }
            return false;
        }

        public int characteristics() {
            return (fence < 0 || est == map.size ? Spliterator.SIZED : 0) |
                    Spliterator.DISTINCT;
        }
    }

    static final class ValueSpliterator<K,V>
            extends HashMapSpliterator<K,V>
            implements Spliterator<V> {
        ValueSpliterator(HashMap<K,V> m, int origin, int fence, int est,
                         int expectedModCount) {
            super(m, origin, fence, est, expectedModCount);
        }

        public ValueSpliterator<K,V> trySplit() {
            int hi = getFence(), lo = index, mid = (lo + hi) >>> 1;
            return (lo >= mid || current != null) ? null :
                    new ValueSpliterator<>(map, lo, index = mid, est >>>= 1,
                            expectedModCount);
        }

        public void forEachRemaining(Consumer<? super V> action) {
            int i, hi, mc;
            if (action == null)
                throw new NullPointerException();
            HashMap<K,V> m = map;
            Node<K,V>[] tab = m.table;
            if ((hi = fence) < 0) {
                mc = expectedModCount = m.modCount;
                hi = fence = (tab == null) ? 0 : tab.length;
            }
            else
                mc = expectedModCount;
            if (tab != null && tab.length >= hi &&
                    (i = index) >= 0 && (i < (index = hi) || current != null)) {
                Node<K,V> p = current;
                current = null;
                do {
                    if (p == null)
                        p = tab[i++];
                    else {
                        action.accept(p.value);
                        p = p.next;
                    }
                } while (p != null || i < hi);
                if (m.modCount != mc)
                    throw new ConcurrentModificationException();
            }
        }

        public boolean tryAdvance(Consumer<? super V> action) {
            int hi;
            if (action == null)
                throw new NullPointerException();
            Node<K,V>[] tab = map.table;
            if (tab != null && tab.length >= (hi = getFence()) && index >= 0) {
                while (current != null || index < hi) {
                    if (current == null)
                        current = tab[index++];
                    else {
                        V v = current.value;
                        current = current.next;
                        action.accept(v);
                        if (map.modCount != expectedModCount)
                            throw new ConcurrentModificationException();
                        return true;
                    }
                }
            }
            return false;
        }

        public int characteristics() {
            return (fence < 0 || est == map.size ? Spliterator.SIZED : 0);
        }
    }

    static final class EntrySpliterator<K,V>
            extends HashMapSpliterator<K,V>
            implements Spliterator<Map.Entry<K,V>> {
        EntrySpliterator(HashMap<K,V> m, int origin, int fence, int est,
                         int expectedModCount) {
            super(m, origin, fence, est, expectedModCount);
        }

        public EntrySpliterator<K,V> trySplit() {
            int hi = getFence(), lo = index, mid = (lo + hi) >>> 1;
            return (lo >= mid || current != null) ? null :
                    new EntrySpliterator<>(map, lo, index = mid, est >>>= 1,
                            expectedModCount);
        }

        public void forEachRemaining(Consumer<? super Map.Entry<K,V>> action) {
            int i, hi, mc;
            if (action == null)
                throw new NullPointerException();
            HashMap<K,V> m = map;
            Node<K,V>[] tab = m.table;
            if ((hi = fence) < 0) {
                mc = expectedModCount = m.modCount;
                hi = fence = (tab == null) ? 0 : tab.length;
            }
            else
                mc = expectedModCount;
            if (tab != null && tab.length >= hi &&
                    (i = index) >= 0 && (i < (index = hi) || current != null)) {
                Node<K,V> p = current;
                current = null;
                do {
                    if (p == null)
                        p = tab[i++];
                    else {
                        action.accept(p);
                        p = p.next;
                    }
                } while (p != null || i < hi);
                if (m.modCount != mc)
                    throw new ConcurrentModificationException();
            }
        }

        public boolean tryAdvance(Consumer<? super Map.Entry<K,V>> action) {
            int hi;
            if (action == null)
                throw new NullPointerException();
            Node<K,V>[] tab = map.table;
            if (tab != null && tab.length >= (hi = getFence()) && index >= 0) {
                while (current != null || index < hi) {
                    if (current == null)
                        current = tab[index++];
                    else {
                        Node<K,V> e = current;
                        current = current.next;
                        action.accept(e);
                        if (map.modCount != expectedModCount)
                            throw new ConcurrentModificationException();
                        return true;
                    }
                }
            }
            return false;
        }

        public int characteristics() {
            return (fence < 0 || est == map.size ? Spliterator.SIZED : 0) |
                    Spliterator.DISTINCT;
        }
    }

    /* ------------------------------------------------------------ */
    // LinkedHashMap support


    /*
     * The following package-protected methods are designed to be
     * overridden by LinkedHashMap, but not by any other subclass.
     * Nearly all other internal methods are also package-protected
     * but are declared final, so can be used by LinkedHashMap, view
     * classes, and HashSet.
     */

    // Create a regular (non-tree) node
    Node<K,V> newNode(int hash, K key, V value, Node<K,V> next) {
        return new Node<>(hash, key, value, next);
    }

    // For conversion from TreeNodes to plain nodes
    Node<K,V> replacementNode(Node<K,V> p, Node<K,V> next) {
        return new Node<>(p.hash, p.key, p.value, next);
    }

    // Create a tree bin node
    TreeNode<K,V> newTreeNode(int hash, K key, V value, Node<K,V> next) {
        return new TreeNode<>(hash, key, value, next);
    }

    // For treeifyBin
    TreeNode<K,V> replacementTreeNode(Node<K,V> p, Node<K,V> next) {
        return new TreeNode<>(p.hash, p.key, p.value, next);
    }

    /**
     * Reset to initial default state.  Called by clone and readObject.
     */
    void reinitialize() {
        table = null;
        entrySet = null;
        keySet = null;
        values = null;
        modCount = 0;
        threshold = 0;
        size = 0;
    }

    // Callbacks to allow LinkedHashMap post-actions
    void afterNodeAccess(Node<K,V> p) { }
    void afterNodeInsertion(boolean evict) { }
    void afterNodeRemoval(Node<K,V> p) { }

    // Called only from writeObject, to ensure compatible ordering.
    void internalWriteEntries(java.io.ObjectOutputStream s) throws IOException {
        Node<K,V>[] tab;
        if (size > 0 && (tab = table) != null) {
            for (int i = 0; i < tab.length; ++i) {
                for (Node<K,V> e = tab[i]; e != null; e = e.next) {
                    s.writeObject(e.key);
                    s.writeObject(e.value);
                }
            }
        }
    }

    /* ------------------------------------------------------------ */
    // Tree bins

    /**
     * Entry for Tree bins. Extends LinkedHashMap.Entry (which in turn
     * extends Node) so can be used as extension of either regular or
     * linked node.
     */
    static final class TreeNode<K,V> extends LinkedHashMap.Entry<K,V> {
        TreeNode<K,V> parent;  // red-black tree links
        TreeNode<K,V> left;
        TreeNode<K,V> right;
        TreeNode<K,V> prev;    // needed to unlink next upon deletion
        boolean red;
        TreeNode(int hash, K key, V val, Node<K,V> next) {
            super(hash, key, val, next);
        }

        /**
         * Returns root of tree containing this node.
         */
        final TreeNode<K,V> root() {
            for (TreeNode<K,V> r = this, p;;) {
                if ((p = r.parent) == null)
                    return r;
                r = p;
            }
        }

        /**
         * 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;
            if (root != null && tab != null && (n = tab.length) > 0) {
                int index = (n - 1) & root.hash;
                TreeNode<K,V> first = (TreeNode<K,V>)tab[index];
                if (root != first) {
                    Node<K,V> rn;
                    tab[index] = root;
                    TreeNode<K,V> rp = root.prev;
                    if ((rn = root.next) != null)
                        ((TreeNode<K,V>)rn).prev = rp;
                    if (rp != null)
                        rp.next = rn;
                    if (first != null)
                        first.prev = root;
                    root.next = first;
                    root.prev = null;
                }
                assert checkInvariants(root);
            }
        }

        /**
         * 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) {
            TreeNode<K,V> p = this;
            do {
                int ph, dir; K pk;
                TreeNode<K,V> pl = p.left, pr = p.right, q;
                if ((ph = p.hash) > h)
                    p = pl;
                else if (ph < h)
                    p = pr;
                else if ((pk = p.key) == k || (k != null && k.equals(pk)))
                    return p;
                else if (pl == null)
                    p = pr;
                else if (pr == null)
                    p = pl;
                else if ((kc != null ||
                        (kc = comparableClassFor(k)) != null) &&
                        (dir = compareComparables(kc, k, pk)) != 0)
                    p = (dir < 0) ? pl : pr;
                else if ((q = pr.find(h, k, kc)) != null)
                    return q;
                else
                    p = pl;
            } while (p != null);
            return null;
        }

        /**
         * Calls find for root node.
         */
        final TreeNode<K,V> getTreeNode(int h, Object k) {
            return ((parent != null) ? root() : this).find(h, k, null);
        }

        /**
         * Tie-breaking utility for ordering insertions when equal
         * hashCodes and non-comparable. We don't require a total
         * order, just a consistent insertion rule to maintain
         * equivalence across rebalancings. Tie-breaking further than
         * necessary simplifies testing a bit.
         */
        static int tieBreakOrder(Object a, Object b) {
            int d;
            if (a == null || b == null ||
                    (d = a.getClass().getName().
                            compareTo(b.getClass().getName())) == 0)
                d = (System.identityHashCode(a) <= System.identityHashCode(b) ?
                        -1 : 1);
            return d;
        }

        /**
         * Forms tree of the nodes linked from this node.
         */
        final void treeify(Node<K,V>[] tab) {
            TreeNode<K,V> root = null;
            for (TreeNode<K,V> x = this, next; x != null; x = next) {
                next = (TreeNode<K,V>)x.next;
                x.left = x.right = null;
                if (root == null) {
                    x.parent = null;
                    x.red = false;
                    root = x;
                }
                else {
                    K k = x.key;
                    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;
                        else if ((kc == null &&
                                (kc = comparableClassFor(k)) == null) ||
                                (dir = compareComparables(kc, k, pk)) == 0)
                            dir = tieBreakOrder(k, pk);

                        TreeNode<K,V> xp = p;
                        if ((p = (dir <= 0) ? p.left : p.right) == null) {
                            x.parent = xp;
                            if (dir <= 0)
                                xp.left = x;
                            else
                                xp.right = x;
                            root = balanceInsertion(root, x);
                            break;
                        }
                    }
                }
            }
            moveRootToFront(tab, root);
        }

        /**
         * 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<K,V> p = map.replacementNode(q, null);
                if (tl == null)
                    hd = p;
                else
                    tl.next = p;
                tl = p;
            }
            return hd;
        }

        /**
         * 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;
            TreeNode<K,V> root = (parent != null) ? root() : this;
            for (TreeNode<K,V> p = root;;) {
                int dir, ph; K pk;
                if ((ph = p.hash) > h)
                    dir = -1;
                else if (ph < h)
                    dir = 1;
                else if ((pk = p.key) == k || (k != null && k.equals(pk)))
                    return p;
                else if ((kc == null &&
                        (kc = comparableClassFor(k)) == null) ||
                        (dir = compareComparables(kc, k, pk)) == 0) {
                    if (!searched) {
                        TreeNode<K,V> q, ch;
                        searched = true;
                        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 = tieBreakOrder(k, pk);
                }

                TreeNode<K,V> xp = p;
                if ((p = (dir <= 0) ? p.left : p.right) == null) {
                    Node<K,V> xpn = xp.next;
                    TreeNode<K,V> x = map.newTreeNode(h, k, v, xpn);
                    if (dir <= 0)
                        xp.left = x;
                    else
                        xp.right = 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;
                }
            }
        }

        /**
         * 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;
            if (tab == null || (n = tab.length) == 0)
                return;
            int index = (n - 1) & hash;
            TreeNode<K,V> first = (TreeNode<K,V>)tab[index], root = first, rl;
            TreeNode<K,V> succ = (TreeNode<K,V>)next, pred = prev;
            if (pred == null)
                tab[index] = first = succ;
            else
                pred.next = succ;
            if (succ != null)
                succ.prev = pred;
            if (first == null)
                return;
            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;
            }
            TreeNode<K,V> p = this, pl = left, pr = right, replacement;
            if (pl != null && pr != null) {
                TreeNode<K,V> s = pr, sl;
                while ((sl = s.left) != null) // find successor
                    s = sl;
                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;
                if (s == pr) { // p was s's direct parent
                    p.parent = s;
                    s.right = p;
                }
                else {
                    TreeNode<K,V> sp = s.parent;
                    if ((p.parent = sp) != null) {
                        if (s == sp.left)
                            sp.left = p;
                        else
                            sp.right = p;
                    }
                    if ((s.right = pr) != null)
                        pr.parent = s;
                }
                p.left = null;
                if ((p.right = sr) != null)
                    sr.parent = p;
                if ((s.left = pl) != null)
                    pl.parent = s;
                if ((s.parent = pp) == null)
                    root = s;
                else if (p == pp.left)
                    pp.left = s;
                else
                    pp.right = s;
                if (sr != null)
                    replacement = sr;
                else
                    replacement = p;
            }
            else if (pl != null)
                replacement = pl;
            else if (pr != null)
                replacement = pr;
            else
                replacement = p;
            if (replacement != p) {
                TreeNode<K,V> pp = replacement.parent = p.parent;
                if (pp == null)
                    root = replacement;
                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);

            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);
        }

        /**
         * 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;
            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;
                }
            }

            if (loHead != null) {
                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) {
                if (hc <= UNTREEIFY_THRESHOLD)
                    tab[index + bit] = hiHead.untreeify(map);
                else {
                    tab[index + bit] = hiHead;
                    if (loHead != null)
                        hiHead.treeify(tab);
                }
            }
        }

        /* ------------------------------------------------------------ */
        // Red-black tree methods, all adapted from CLR

        static <K,V> TreeNode<K,V> rotateLeft(TreeNode<K,V> root,
                                              TreeNode<K,V> p) {
            TreeNode<K,V> r, pp, rl;
            if (p != null && (r = p.right) != null) {
                if ((rl = p.right = r.left) != null)
                    rl.parent = p;
                if ((pp = r.parent = p.parent) == null)
                    (root = r).red = false;
                else if (pp.left == p)
                    pp.left = r;
                else
                    pp.right = r;
                r.left = p;
                p.parent = r;
            }
            return root;
        }

        static <K,V> TreeNode<K,V> rotateRight(TreeNode<K,V> root,
                                               TreeNode<K,V> p) {
            TreeNode<K,V> l, pp, lr;
            if (p != null && (l = p.left) != null) {
                if ((lr = p.left = l.right) != null)
                    lr.parent = p;
                if ((pp = l.parent = p.parent) == null)
                    (root = l).red = false;
                else if (pp.right == p)
                    pp.right = l;
                else
                    pp.left = l;
                l.right = p;
                p.parent = l;
            }
            return root;
        }

        static <K,V> TreeNode<K,V> balanceInsertion(TreeNode<K,V> root,
                                                    TreeNode<K,V> x) {
            x.red = true;
            for (TreeNode<K,V> xp, xpp, xppl, xppr;;) {
                if ((xp = x.parent) == null) {
                    x.red = false;
                    return x;
                }
                else if (!xp.red || (xpp = xp.parent) == null)
                    return root;
                if (xp == (xppl = xpp.left)) {
                    if ((xppr = xpp.right) != null && xppr.red) {
                        xppr.red = false;
                        xp.red = false;
                        xpp.red = true;
                        x = xpp;
                    }
                    else {
                        if (x == xp.right) {
                            root = rotateLeft(root, x = xp);
                            xpp = (xp = x.parent) == null ? null : xp.parent;
                        }
                        if (xp != null) {
                            xp.red = false;
                            if (xpp != null) {
                                xpp.red = true;
                                root = rotateRight(root, xpp);
                            }
                        }
                    }
                }
                else {
                    if (xppl != null && xppl.red) {
                        xppl.red = false;
                        xp.red = false;
                        xpp.red = true;
                        x = xpp;
                    }
                    else {
                        if (x == xp.left) {
                            root = rotateRight(root, x = xp);
                            xpp = (xp = x.parent) == null ? null : xp.parent;
                        }
                        if (xp != null) {
                            xp.red = false;
                            if (xpp != null) {
                                xpp.red = true;
                                root = rotateLeft(root, xpp);
                            }
                        }
                    }
                }
            }
        }

        static <K,V> TreeNode<K,V> balanceDeletion(TreeNode<K,V> root,
                                                   TreeNode<K,V> x) {
            for (TreeNode<K,V> xp, xpl, xpr;;) {
                if (x == null || x == root)
                    return root;
                else if ((xp = x.parent) == null) {
                    x.red = false;
                    return x;
                }
                else if (x.red) {
                    x.red = false;
                    return root;
                }
                else if ((xpl = xp.left) == x) {
                    if ((xpr = xp.right) != null && xpr.red) {
                        xpr.red = false;
                        xp.red = true;
                        root = rotateLeft(root, xp);
                        xpr = (xp = x.parent) == null ? null : xp.right;
                    }
                    if (xpr == null)
                        x = xp;
                    else {
                        TreeNode<K,V> sl = xpr.left, sr = xpr.right;
                        if ((sr == null || !sr.red) &&
                                (sl == null || !sl.red)) {
                            xpr.red = true;
                            x = xp;
                        }
                        else {
                            if (sr == null || !sr.red) {
                                if (sl != null)
                                    sl.red = false;
                                xpr.red = true;
                                root = rotateRight(root, xpr);
                                xpr = (xp = x.parent) == null ?
                                        null : xp.right;
                            }
                            if (xpr != null) {
                                xpr.red = (xp == null) ? false : xp.red;
                                if ((sr = xpr.right) != null)
                                    sr.red = false;
                            }
                            if (xp != null) {
                                xp.red = false;
                                root = rotateLeft(root, xp);
                            }
                            x = root;
                        }
                    }
                }
                else { // symmetric
                    if (xpl != null && xpl.red) {
                        xpl.red = false;
                        xp.red = true;
                        root = rotateRight(root, xp);
                        xpl = (xp = x.parent) == null ? null : xp.left;
                    }
                    if (xpl == null)
                        x = xp;
                    else {
                        TreeNode<K,V> sl = xpl.left, sr = xpl.right;
                        if ((sl == null || !sl.red) &&
                                (sr == null || !sr.red)) {
                            xpl.red = true;
                            x = xp;
                        }
                        else {
                            if (sl == null || !sl.red) {
                                if (sr != null)
                                    sr.red = false;
                                xpl.red = true;
                                root = rotateLeft(root, xpl);
                                xpl = (xp = x.parent) == null ?
                                        null : xp.left;
                            }
                            if (xpl != null) {
                                xpl.red = (xp == null) ? false : xp.red;
                                if ((sl = xpl.left) != null)
                                    sl.red = false;
                            }
                            if (xp != null) {
                                xp.red = false;
                                root = rotateRight(root, xp);
                            }
                            x = root;
                        }
                    }
                }
            }
        }

        /**
         * Recursive invariant check
         */
        static <K,V> boolean checkInvariants(TreeNode<K,V> t) {
            TreeNode<K,V> tp = t.parent, tl = t.left, tr = t.right,
                    tb = t.prev, tn = (TreeNode<K,V>)t.next;
            if (tb != null && tb.next != t)
                return false;
            if (tn != null && tn.prev != t)
                return false;
            if (tp != null && t != tp.left && t != tp.right)
                return false;
            if (tl != null && (tl.parent != t || tl.hash > t.hash))
                return false;
            if (tr != null && (tr.parent != t || tr.hash < t.hash))
                return false;
            if (t.red && tl != null && tl.red && tr != null && tr.red)
                return false;
            if (tl != null && !checkInvariants(tl))
                return false;
            if (tr != null && !checkInvariants(tr))
                return false;
            return true;
        }
    }

}

三.问题

1.HashMap1.7和1.8的区别

(1)底层结构

   Java 1.7中的HashMap底层结构是由Entry数组和单项链表组成的。

   Java 1.8中的HashMap则是由Node数组、链表和红黑树组成的。当链表长度超过8且数组长度超过64时,链表会被转换为红黑树以提高性能。

(2)扩容策略

    Java 1.7中,扩容触发条件是当初始化或size超过阈值时,扩容后的数组大小为之前的两倍。在扩容过程中,原数组中索引相同的元素只会继续保存在该索引位置或者两倍的索引位置。

    Java 1.8中,扩容触发条件同样包括初始化或size超过阈值时,但还有一个条件是链表上节点数量超过8时会调用treeifyBin()方法,如果数组长度小于64则会触发resize()扩容方法。

(3)插入方式

    Java 1.7中,HashMap的put()方法采用的是头插法。这可能导致在并发扩容时出现循环链表问题,造成死循环。

    Java 1.8中,HashMap的put()方法改为了尾插法。虽然尾插法解决了1.7中的循环链表问题,但在红黑树内部并发插入时仍有可能造成死循环问题。

2.HashMap1.8为什么改为尾插法?

(1)减少死链问题:在并发环境下,头插法可能导致链表在扩容时产生死循环,即形成环型链表。尾插法可以减少这种情况的发生,从而提高HashMap的可靠性。

(2)提高性能:尾插法有助于减少链表的长度,从而减少查找、插入和删除元素时的性能下降。当链表长度增加时,头插法可能导致链表变得非常长,影响性能。尾插法通过将新元素追加到链表末尾,有助于保持链表的短小,减少冲突引起的性能下降。

 (3)更适合并发操作:尾插法在进行并发操作时更有利。由于头插法总是在链表的头部进行操作,可能导致多个线程在同一个桶的链表头部争夺锁,增加了竞争和锁的争用。尾插法将新元素添加到链表末尾,减少了争夺同一个锁的概率,从而提高了并发性能。

 (4)保持插入顺序:尾插法有助于保持元素插入的顺序,这对于某些应用来说可能是重要的特性。当遍历HashMap时,元素的顺序与它们被插入的顺序相同。

  (5)优化数据结构:Java 8还引入了红黑树结构,当一个桶中的链表长度超过一定阈值时,HashMap会将这个链表转换为一棵红黑树。这种改进可以进一步提高查找某个键值对的性能,尤其是在键值对数量非常大时。

3.HashMap1.7循环链表问题

//HashMap1.7源码 

  void resize(int newCapacity) {
        Entry[] oldTable = table;
        int oldCapacity = oldTable.length;
        if (oldCapacity == MAXIMUM_CAPACITY) {
            threshold = Integer.MAX_VALUE;
            return;
        }
        //根据原来的table容量生成一个2倍的容量的table
        Entry[] newTable = new Entry[newCapacity];
        //将所有Entry从当前表转移到newTable(问题就在transfer方法中)
        transfer(newTable, initHashSeedAsNeeded(newCapacity));
        table = newTable;
        threshold = (int)Math.min(newCapacity * loadFactor, MAXIMUM_CAPACITY + 1);
    }
void transfer(Entry[] newTable, boolean rehash) {
        int newCapacity = newTable.length;
        //遍历table数组
        for (Entry<K,V> e : table) {
            //遍历table中的链表
            while(null != e) {
               //定义next
                Entry<K,V> next = e.next;
                //如果是重新hash,则需要重新计算hash值
                if (rehash) {
                    e.hash = null == e.key ? 0 : hash(e.key);
                }
                //定位Hash桶
                int i = indexFor(e.hash, newCapacity);
                //元素连接到桶中,这里相当于单链表的插入,总是插入在最前面,指针指向它下面的一个元素
                e.next = newTable[i];
                //newTable[i]总是最新插入的值
                newTable[i] = e;
                //继续下一个元素
                e = next;
            }
        }
    }

例子:链表中一个Entry插入新数组的四步操作

单线程环境下,链表插入新数组

多线程环境下,假如有A,B两个线程,A线程执行执行完第一步(Entry<K,V> next = e.next;)就阻塞了,线程B方法执行完了以后,线程A继续执行。

标签:hash,HashMap,tab,int,就够,源码,key,null,节点
From: https://blog.csdn.net/qq_45800511/article/details/136693147

相关文章

  • 【前端素材】推荐优质多用途肉类品商城网站设计Meatza平台模板(附源码)
    一、需求分析多用途肉类品商城网页是一个在线平台,专门销售各种肉类及相关产品的电子商城。以下是这类网页通常具备的具体功能:产品分类:网页会根据不同种类的肉类进行分类,如牛肉、猪肉、禽类、海鲜等,方便用户查找所需产品。产品展示:网页会展示各种肉类产品的图片、价格、产......
  • 【附源码】JAVA计算机毕业设计音乐豆瓣(springboot+mysql+开题+论文)
    本系统(程序+源码)带文档lw万字以上 文末可获取一份本项目的java源码和数据库参考。系统程序文件列表开题报告内容研究背景随着信息技术的迅猛发展,音乐作为人们日常生活中不可或缺的一部分,其获取与分享方式也在不断地变革。传统的音乐获取途径,如购买唱片或到实体音乐店挑选......
  • MyBatis3源码深度解析(二十一)动态SQL实现原理(二)动态SQL解析过程、#{}和${}的区别
    文章目录前言8.5动态SQL解析过程8.5.1SQL配置转换为SqlSource对象8.5.2SqlSource转换为静态SQL语句8.6#{}和${}的区别8.7小结前言在【MyBatis3源码深度解析(二十)动态SQL实现原理(一)动态SQL的核心组件】中研究了MyBatis动态SQL相关的组件,如SqlSource用于描述......
  • Grafana源码启动
    Grafana源码启动因为项目用到Grafana,但是用iframe嵌入前端。想研究一下源码看有没有可能直接用组件嵌入,然后用API调用Grafana的服务。GrafanabackendGrafana的后端服务是用Go写的,新语言,有待学习。Grafanafrontend前端使用React、Angular编写的Typescript项目。框架没学习过......
  • 源码!大学生兼职跟踪系统ssm+vue+mysql
    大学生兼职跟踪系统java+ssm+vue+mysql摘要演示视频系统开发流程系统结构设计系统主要功能介绍管理员功能模块个人中心商家管理学生管理兼职招聘管理兼职应聘管理论坛管理学生前后台功能模块兼职招聘兼职论坛开发环境后端:前端:数据库:!!!有需要的小伙伴可以点击下方链接直......
  • 源码!病人跟踪治疗信息管理系统(ssm+vue)
    病人跟踪治疗信息管理系统java+ssm+vue摘要演示视频系统功能结构病人跟踪治疗信息管理系统的结构图所示:登录结构图:系统主要功能介绍系统功能分析病例采集管理医生管理行动轨迹管理核酸检测报告管理预约管理开发环境后端:前端:数据库:!!!有需要的小伙伴可以点击下方链接直接......
  • HashMap的底层设计
    底层数据结构在jdk1.7及它之前是数组+链表;在jdk1.8极其之后,是数组+(链表|红黑树)jdk1.8数组索引计算staticfinalinthash(Objectkey){inth;return(key==null)?0:(h=key.hashCode())^(h>>>16);}而索引值等于hash值和数组长度减一作与运......
  • 基于SpringBoot+Vue的健身教练预约管理系统(源码+文档+部署+讲解)
    毕设帮助、定制开发、源码交流联系方式见文末。一.系统概述私人健身与教练预约管理系统,可以摆脱传统手写记录的管理模式。利用计算机系统,进行用户信息、管理员信息的管理,其中包含首页,个人中心,用户管理,教练管理,健身项目管理,项目分类,教练信息管理,教练预约管理,系统管理等功......
  • 【附源码】java松江大学城就餐推荐系统设计与实现(ssm毕业设计+maven+vue+计算机专业)
    本系统(程序+源码)带文档lw万字以上  文末可领取本课题的JAVA源码参考系统程序文件列表系统的选题背景和意义选题背景:在现代都市的快节奏生活中,餐饮服务已经成为人们日常生活中不可或缺的一部分。尤其是对于大学生这一群体,他们通常生活在学校周边的大学城,拥有丰富的就餐选......
  • 智能停车场管理系统设计与实现|jsp+ Mysql+Java+ B/S结构(可运行源码+数据库+设计文档
    本项目包含可运行源码+数据库+LW,文末可获取本项目的所有资料。推荐阅读100套最新项目最新ssm+java项目文档+视频演示+可运行源码分享最新jsp+java项目文档+视频演示+可运行源码分享最新SpringBoot项目文档+视频演示+可运行源码分享2024年56套包含java,ssm,springboot的平台......