Java 源码阅读——HashMap

300 阅读17分钟

写在前面:自己学习Java源码的一些笔记,JDK版本为1.8.0_131

HashMap的底层结构Node<K,V>

  如果使用过 HashMap 这个数据结构,应该知道HashMap用于存储 key - value(键值对)这样的数据,每一个 key 只能对应一个 value。当往 HashMap 中添加已有的 key,新的 value 会覆盖原来的 value。

  HashMap所涉及到的数据结构有数组、链表和红黑树。HashMap底层是Node<K,V>组成的数组 table,table数组根据 hash 值被分为一个个桶,每个桶中存储着一条链表(或者红黑树),表现为Node<K,V>[]数组的每个元素存储着链表的头结点(或红黑树的根节点)。其中最基本元素Node<K,V>的源代码如下:

    /**
     * Basic hash bin node, used for most entries.  (See below for
     * TreeNode subclass, and in LinkedHashMap for its Entry subclass.)
     */
    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; }
        
        // Node<K,V>的hashCode方法结果为key的hashCode结果与value的hashCode结果的异或。
        // Objects.hashCode()传入null返回0,其他调用Object的hashCode方法
        // Object的 hashCode 方法是一个native方法,JDK8中从注释看大致为将对象的地址转换成一个int值返回
        public final int hashCode() {
            return Objects.hashCode(key) ^ Objects.hashCode(value);
        }
        
        // 只允许修改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;
        }
    }

  Node<K,V>类有四个属性,分别是hash、key、value 和 next。hash 存储 key 的 hash 值,key 和 value 是键值对,next 指向下一个 Node<K,V> 结点。

HashMap中的hash值

1. hash(Object key)

  HashMap 的方法用于得到 key 的 hash 值。hash 值被用来确定某个键值对应当被存储在 HashMap 中的哪个桶内,同一个桶内的键值对元素它们 key 所对应的 hash 值相同。在 HashMap 的 hash 方法中,key 为 null 时直接返回 0,否则调用 key 对应类的 hashCode() 方法得到中间值 h,再将 h 右移16位的结果与原 h 异或,相当于保留 h 的高16位,将 h 的低16位与高16位做异或运算,得到最终的 hash 值。这个 hash 值的范围仍然是 int 范围。在之后的过程中,还会对这个hash值映射到Node<K,V>的索引范围内。

  知乎上关于 hash 值有个很好的回答:JDK 源码中 HashMap 的 hash 方法原理是什么? - 胖君的回答 - 知乎

    /**
     * Computes key.hashCode() and spreads (XORs) higher bits of hash
     * to lower.  Because the table uses power-of-two masking, sets of
     * hashes that vary only in bits above the current mask will
     * always collide. (Among known examples are sets of Float keys
     * holding consecutive whole numbers in small tables.)  So we
     * apply a transform that spreads the impact of higher bits
     * downward. There is a tradeoff between speed, utility, and
     * quality of bit-spreading. Because many common sets of hashes
     * are already reasonably distributed (so don't benefit from
     * spreading), and because we use trees to handle large sets of
     * collisions in bins, we just XOR some shifted bits in the
     * cheapest possible way to reduce systematic lossage, as well as
     * to incorporate impact of the highest bits that would otherwise
     * never be used in index calculations because of table bounds.
     */
    static final int hash(Object key) {
        int h;
        // 对于key为null,统一返回0
        // 不为null,调用key所属的类中的hashCode方法存储到h中
        // h保留高16位,低16位与高16位做异或运算
        // 得到的结果是一个int范围内的值
        return (key == null) ? 0 : (h = key.hashCode()) ^ (h >>> 16);
    }

2. (n - 1) & hash

  HashMap 中的 hash 方法得到的结果是一个 int 范围内的值,显然不能直接用于桶的划分。将 hash 值映射入 Node<K,V>[] 的索引范围最朴素的想法是 hash 值对数组的长度取余, 即 hash % n,这样可以保证每一个 hash 值都能对应在索引范围内。

  实际上Java的源码中使用的是 (n - 1) & hash 运算,在往HashMap中插入键值对的方法putVal()中使用到了这一运算。将 hash 值与数组长度减一做与运算在实际上的效果与 hash % n 相同,前提是 n 为 2 的 N 次幂。当 n 为 2 的 N 次幂的时候, n - 1的二进制表示低位全部为 1,做与运算相当于保留 hash 的低位的值,且被保留部分转换为十进制后一定在Node<K,V>数组的索引范围内。

    // 这段代码的意思是如果某个桶内没有结点,将输入的键值对作为结点加入桶中
    if ((p = tab[i = (n - 1) & hash]) == null)
        tab[i] = newNode(hash, key, value, null);

HashMap的结构的初始化

1. HashMap的构造方法

  HashMap 的初始化并不会实际构建底层的 table,而是在第一次往 HashMap 中插入元素之前构建。先看下 HashMap 的构造方法做了什么工作。

  • 无参构造器
    /**
     * Constructs an empty <tt>HashMap</tt> with the default initial capacity
     * (16) and the default load factor (0.75).
     */
    public HashMap() {
        // 默认的装载因子为 16
        this.loadFactor = DEFAULT_LOAD_FACTOR; // all other fields defaulted
    }

  无参构造器只初始化了装载因子为 16。

  • 有参构造器1
    /**
     * Constructs an empty <tt>HashMap</tt> with the specified initial
     * capacity and the default load factor (0.75).
     *
     * @param  initialCapacity the initial capacity.
     * @throws IllegalArgumentException if the initial capacity is negative.
     */
    public HashMap(int initialCapacity) {
        this(initialCapacity, DEFAULT_LOAD_FACTOR);
    }

  一个参数的有参构造器能够传入一个 int 类型的参数,指定 HashMap 的初始容量。

  • 有参构造器2
    /**
     * Constructs an empty <tt>HashMap</tt> with the specified initial
     * capacity and load factor.
     *
     * @param  initialCapacity the initial capacity
     * @param  loadFactor      the load factor
     * @throws IllegalArgumentException if the initial capacity is negative
     *         or the load factor is nonpositive
     */
    public HashMap(int initialCapacity, float loadFactor) {
        // 容量自然不能为负数
        if (initialCapacity < 0)
            throw new IllegalArgumentException("Illegal initial capacity: " +
                                               initialCapacity);
        // 如果初始的容量大于 2 的 30 次方,默认初始容量为 2 的 30 次方大小,实际上容量达到这个大小,HashMap 不会再扩容。
        if (initialCapacity > MAXIMUM_CAPACITY)
            initialCapacity = MAXIMUM_CAPACITY;
        if (loadFactor <= 0 || Float.isNaN(loadFactor))
            throw new IllegalArgumentException("Illegal load factor: " +
                                               loadFactor);
        // 指定装载因子
        this.loadFactor = loadFactor;
        // tableSizeFor() 方法可以获得大于等于输入参数且最近的2的整数次幂的数
        // 调用这个方法,threshold 会是一个 2 的整数次幂
        this.threshold = tableSizeFor(initialCapacity);
    }

  有参构造器 2 既可以指定 HashMap 的初始容量,也可以指定装载因子的大小。

2. tableSizeFor(int cap)

  n 由 cap 减一得来,是一个比 cap 小的 32 位的二进制数,对于 n,我们只需要关注其最高位的 1。当将 n 右移一位并与原 n 的结果做或运算后,原 n 最高位的 1 的后一位也被置为 1。以次类推,最终的结果就是原 n 最高位的 1 后面的二进制位全部变为了 1,将这个结果加一一定是一个 2 的整数次幂。至于为何需要先将 cap 减 1 得到 n,考虑 cap 本身就是一个 2 的整数次幂,那么按照前面步骤得到的结果值将是 cap 的两倍,即 cap 左移一位的结果,对 HashMap 而言,只要 table 为 2 的整数次幂即可,因此提前减 1 能够保证 cap 正好为 2 的整数次幂的情况下,该算法得到的结果仍然为 cap。

未命名文件 (1).png

    /**
     * Returns a power of two size for the given target capacity.
     */
    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;
    }

  最终结果使得 n 的最高位的 1 后面的位全部变为了 1。加一后是一个 2 的整数次幂,并且是距离 cap 最近的大于等于 cap 的 2 的整数次幂。

3. HashMap的初始化

  HashMap 的构造器并不会实际构造出 HashMap,只会设定变量的值。无参构造器只会指定 HashMap 的装载因子为默认值 0.75,有参构造器可以指定 HashMap 的初始容量(虽然构造器中参数名字为 initialCapacity,但实际上被设定的变量叫 threshold,中文为阈值),HashMap 并不会直接使用输入的值,而是会寻找一个大于等于用户输入值的最小 2 的整数次幂。

  实际的初始化是在第一次往 HashMap 中添加键值对的时候做的。初始化相关的代码在方法 resize() 中。

    /**
     * Initializes or doubles table size.  If null, allocates in
     * accord with initial capacity target held in field threshold.
     * Otherwise, because we are using power-of-two expansion, the
     * elements from each bin must either stay at same index, or move
     * with a power of two offset in the new table.
     *
     * @return the table
     */
     // 只分析初始化相关
    final Node<K,V>[] resize() {
        Node<K,V>[] oldTab = table;
        // 获取原 table 的容量和 HashMap 的当前阈值,如果是无参构造器,这里两个值都为 0,
        // 如果是有参构造器,oldCap 为 0,
        // oldThr 将会等于 threshold,而这个值正是 tableSizeFor 的结果
        int oldCap = (oldTab == null) ? 0 : oldTab.length;
        int oldThr = threshold;
        int newCap, newThr = 0;
        if (oldCap > 0) {
            // 扩容相关
        }
        // 针对有参构造,newCap 将等于 oldThr,注意此时 newThr 仍然为 0
        else if (oldThr > 0) // initial capacity was placed in threshold
            newCap = oldThr;
        else {               // zero initial threshold signifies using defaults
            // 无参构造初始化时,newCap 被设定为 16, newThr 被设定为 12 (0.75 * 16)
            newCap = DEFAULT_INITIAL_CAPACITY;
            newThr = (int)(DEFAULT_LOAD_FACTOR * DEFAULT_INITIAL_CAPACITY);
        }
        // 有参构造的阈值
        // 如果 table 的容量小于最大允许容量,将被指定为 newCap * loadFactor,
        // 否则 newThr 为 Integer.MAX_VALUE
        if (newThr == 0) {
            float ft = (float)newCap * loadFactor;
            newThr = (newCap < MAXIMUM_CAPACITY && ft < (float)MAXIMUM_CAPACITY ?
                      (int)ft : Integer.MAX_VALUE);
        }
        // threshold 设置为 newThr 的值,此后当 HashMap 中键值对数量超过阈值会触发 HashMap 的扩容机制
        threshold = newThr;
        @SuppressWarnings({"rawtypes","unchecked"})
        // 构建 table
            Node<K,V>[] newTab = (Node<K,V>[])new Node[newCap];
        table = newTab;
        if (oldTab != null) {
            // 原 table 中的内容复制到新的 table 中
        }
        return newTab;

  从源码可以得知 HashMap 的初始化过程中,通过无参创建和有参创建略有不同。

  • 无参构造器创建 HashMap
  1. HashMap 的容量和阈值将会被指定为 16 和 12,装载因子为 0.75,底层 table 将会有 16 个桶
  • 有参构造器创建 HashMap
  1. 首先创建前 HashMap 的属性 threshold 等于,有参构造器输入参数调用了 tableSizeFor() 方法的结果,将 threshold 赋值给 oldThr
  2. newCap = oldThr,随后计算 newThr,等于 newCap * loadFactor(loadFactor 可以由用户指定),如果超过最大允许容量,newThr 将等于 Integer.MAX_VALUE
  3. threshold = newThr,创建 table,table 内桶的数量等于 newCap。

HashMap 键值对的添加及扩容

HashMap 键值对的添加

  put() 方法可以将输入的键值对添加到哈希表中。调用了核心方法putVal()。往 HashMap 中添加键值对首先会检查是否需要对 HashMap 底层的 table 做扩容。当插入时,会根据 key 的 hash () 结果确定出会存入哪一个桶(前文有解释),当这个桶内有元素,会把键值对加在链表的最后,JDK 1.8 还对 HashMap 有优化,当 HashMap 中键值对数量达到某一条件,还会对链表进行树化,转换为红黑树。

    /**
     * Associates the specified value with the specified key in this map.
     * If the map previously contained a mapping for the key, the old
     * value is replaced.
     *
     * @param key key with which the specified value is to be associated
     * @param value value to be associated with the specified key
     * @return the previous value associated with <tt>key</tt>, or
     *         <tt>null</tt> if there was no mapping for <tt>key</tt>.
     *         (A <tt>null</tt> return can also indicate that the map
     *         previously associated <tt>null</tt> with <tt>key</tt>.)
     */
    public V put(K key, V value) {
        return putVal(hash(key), key, value, false, true);
    }
    
    /**
     * Implements Map.put and related methods
     *
     * @param hash hash for key
     * @param key the key
     * @param value the value to put
     * @param onlyIfAbsent if true, don't change existing value
     * @param evict if false, the table is in creation mode.
     * @return previous value, or null if none
     */
    final V putVal(int hash, K key, V value, boolean onlyIfAbsent,
                   boolean evict) {
        Node<K,V>[] tab; Node<K,V> p; int n, i;
        // 如果table为null或者table的长度为0,调用resize方法对table进行初始化或扩容
        if ((tab = table) == null || (n = tab.length) == 0)
            n = (tab = resize()).length;
        // (n - 1) & hash 为 table 数组的索引,如果对应索引处的结点为 null,
        // 说明该桶还没有结点添加进来,直接在此处放入一个内容是输入键值对的node
        // 当 n 即Node<K,V>数组的长度为 2 的N次幂的时候 hash % n 等于 (n - 1) & hash
        if ((p = tab[i = (n - 1) & hash]) == null)
            tab[i] = newNode(hash, key, value, null);
        // 如果该桶已经有结点了
        else {
            Node<K,V> e; K k;
            // == 比较地址,equals()比较实际内容,可以重写equals()方法来更改判断的规则
            if (p.hash == hash &&
                ((k = p.key) == key || (key != null && key.equals(k))))
                e = p;
            // 如果该桶的头结点是一个树结点,代表该桶内的链表已经红黑树化,
            // 调用红黑树的putTreeVal添加到红黑树中
            else if (p instanceof TreeNode)
                e = ((TreeNode<K,V>)p).putTreeVal(this, tab, hash, key, value);
            else {
                for (int binCount = 0; ; ++binCount) {
                    if ((e = p.next) == null) {
                        p.next = newNode(hash, key, value, null);
                        // bitCount从0开始计数的,而TREEIFY_THRESHOLD是从1算起的
                        // 因为这个循环时从头结点的next开始的
                        // 所以会在往结点添加第9个结点之前判断是否需要树化
                        // 实际树化,还有其它条件
                        if (binCount >= TREEIFY_THRESHOLD - 1) // -1 for 1st
                            // 链表红黑树化
                            treeifyBin(tab, hash);
                        break;
                    }
                    // 链表中有结点的内容跟输入key相同,结束循环,此时 e 就是那个key重复的结点
                    if (e.hash == hash &&
                        ((k = e.key) == key || (key != null && key.equals(k))))
                        break;
                    // 指向下一个结点
                    p = e;
                }
            }
            // e != null 说明HashMap中存在输入的Key,更新其Value为输入的Value
            if (e != null) { // existing mapping for key
                V oldValue = e.value;
                // put()传入的onlyIfAbsent为false,所以会更新value值
                if (!onlyIfAbsent || oldValue == null)
                    e.value = value;
                afterNodeAccess(e);
                // 添加的是 HashMap 中已有的键,返回原 value
                return oldValue;
            }
        }
        ++modCount;
        // 如果超过阈值,扩容
        if (++size > threshold)
            resize();
        afterNodeInsertion(evict);
        // 添加了一个 HashMap 中没有的键值对,返回null
        return null;
    }
    

  因为底层的结构为数组+链表(红黑树),因此实际上可以不断地往里添加键值对,但是这样会导致冲突,桶内元素过多会降低 HashMap 的效率。因此 HashMap 也需要合适的扩容机制。

  HashMap 的扩容不是简单地增加桶的数量,回想一下 key 的 hash 值是如何映射到 table 索引范围内的。(n - 1) & hash; 当扩容以后, n 显然会变化,因此对于某些 key 来说,扩容以后,key 对应的键值对应当移动到另外的桶内!为什么是某些 key,而不是全部的 key 呢?这是因为 HashMap 扩容后新的容量是旧容量的两倍。当 n 变为 2n 的时候,(n - 1) & hash 只会比原来的索引值多一个 2 进制位,如果多的是 0,这个键值对对应的桶不变,如果是 1,这个键值对将会被移动到原索引 + 原容量对应的新索引处。因此只需要知道这一位是 0 还是 1 就可以划分出要移动的键值对和不需要移动的键值对。效率比每个键都重新执行 (n - 1) & hash 要高,这也是为什么 HashMap 的容量一定是 2 的整数次幂。

未命名文件.png

    final Node<K,V>[] resize() {
        Node<K,V>[] oldTab = table;
        // 扩容前获取原容量和阈值
        int oldCap = (oldTab == null) ? 0 : oldTab.length;
        int oldThr = threshold;
        int newCap, newThr = 0;
        if (oldCap > 0) {
            // 当原容量已经大于默认最大容量了,修改阈值为 Integer.MAX_VALUE
            // 直接返回原 table,此后不会再扩容
            if (oldCap >= MAXIMUM_CAPACITY) {
                threshold = Integer.MAX_VALUE;
                return oldTab;
            }
            // 新容量为旧容量的两倍
            // 新的阈值也变为原来的两倍
            else if ((newCap = oldCap << 1) < MAXIMUM_CAPACITY &&
                     oldCap >= DEFAULT_INITIAL_CAPACITY)
                newThr = oldThr << 1; // double threshold
        }
        else if (oldThr > 0) // initial capacity was placed in threshold
            newCap = oldThr;
        else {               // zero initial threshold signifies using defaults
            newCap = DEFAULT_INITIAL_CAPACITY;
            newThr = (int)(DEFAULT_LOAD_FACTOR * DEFAULT_INITIAL_CAPACITY);
        }
        // 当 oldCap < DEFAULT_INITIAL_CAPACITY 会进入这块代码
        if (newThr == 0) {
            float ft = (float)newCap * loadFactor;
            newThr = (newCap < MAXIMUM_CAPACITY && ft < (float)MAXIMUM_CAPACITY ?
                      (int)ft : Integer.MAX_VALUE);
        }
        threshold = newThr;
        @SuppressWarnings({"rawtypes","unchecked"})
            // 创建新的 table
            Node<K,V>[] newTab = (Node<K,V>[])new Node[newCap];
        table = newTab;
        // 将原 table 中的键值对转移到新的 table 中
        if (oldTab != null) {
            for (int j = 0; j < oldCap; ++j) {
                Node<K,V> e;
                // 依次移动每个桶中的元素
                if ((e = oldTab[j]) != null) {
                    oldTab[j] = null;
                    // 如果该桶内只有一个元素,仍然使用 (n - 1) & hash 的方式
                    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
                        // 要将键值对划分为两个链表
                        // loHead、loTail、hiHead、hiTail 分别是两个链表的头尾结点
                        Node<K,V> loHead = null, loTail = null;
                        Node<K,V> hiHead = null, hiTail = null;
                        Node<K,V> next;
                        // 往两个链表内添加结点
                        do {
                            next = e.next;
                            // 根据 hash & oldCap 来判断该划分到哪个链表
                            // 如果是 0 ,添加到 lo 这个链表后面
                            if ((e.hash & oldCap) == 0) {
                                if (loTail == null)
                                    loHead = e;
                                else
                                    loTail.next = e;
                                loTail = e;
                            }
                            // 如果是 1,添加到 hi 这个链表后面
                            else {
                                if (hiTail == null)
                                    hiHead = e;
                                else
                                    hiTail.next = e;
                                hiTail = e;
                            }
                        } while ((e = next) != null);
                        // 此时已把键值对划分为两个链表
                        // lo 的链表存储的是不用存在其他桶的结点
                        // hi 的链表存储的是要更改桶的结点
                        if (loTail != null) {
                            loTail.next = null;
                            newTab[j] = loHead;
                        }
                        // hi 这个链表的索引刚好为原索引 + 原容量
                        if (hiTail != null) {
                            hiTail.next = null;
                            newTab[j + oldCap] = hiHead;
                        }
                    }
                }
            }
        }
        return newTab;
    }

HashMap 的树化

  HashMap 的树化发生在 table 中单个桶内链表结点超过 8 个的时候,但这并不是树化的唯一条件,实际上进入 treeifyBin() 这个方法后,还会判断当前 table 的容量是不是达到了 MIN_TREEIFY_CAPACITY(64),容量大于等于64才会执行树化,否则仍然是进行扩容。因此 HashMap 树化的完整条件为:将要添加结点的 table 中的某个桶内结点数超过 8 个,同时此时的 table 容量大于等于了 64。

    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)
            // table 容量小于 64,会旋转扩容
            resize();
        else if ((e = tab[index = (n - 1) & hash]) != null) {
            // 树化
        }
    }

HashMap 中的 TreeNode

  在解析树化之前,先要明白,当树化发生后,table 中存储的就不是 Node<K,V> 了,而是 TreeNode<K,V>。从源码中我们可以得知,TreeNode<K,V> 继承 LinkedHashMap(LinkedHashMap 是 HashMap 的子类,table 中存储的双向链表,能按插入 LinkedHashMap 的先后顺序遍历) 中的内部类Entry<K,V>,而 Entry<K,V> 又继承 Node<K,V>,因此往 table 是能够存放 TreeNode 的(多态)。

  TreeNode<K,V> 是一个二叉树结构,属性中具有左子节点 left,右子节点 right,还有指向父节点的 parent 属性,及 prev,next 属性,还有标记该树结点颜色的 red 属性。

    /**
     * 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) {
            // 调用了 Entry<K,V> 的构造器,但实际上 Entry<K,V> 也是调用的 Node<K,V> 的构造器
            super(hash, key, val, next);
        }
        
        // TreeNode<K,V>类的方法
        ...
    }

  在正式树化之前,需要先将先将 table 中的 Node<K,V> 元素转换为 TreeNode<K,V>。

    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();
        // 通过 hash 确认是 table 中的哪一个桶,桶内有元素先把每个Node<K,V>转换为TreeNode<K,V>
        else if ((e = tab[index = (n - 1) & hash]) != null) {
            TreeNode<K,V> hd = null, tl = null;
            do {
                // 转换为TreeNode
                TreeNode<K,V> p = replacementTreeNode(e, null);
                // 维护TreeNode的 prev 和 next 属性
                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);
        }
    }
    
    
    // For treeifyBin
    TreeNode<K,V> replacementTreeNode(Node<K,V> p, Node<K,V> next) {
        return new TreeNode<>(p.hash, p.key, p.value, next);
    }

  在执行 hd.treeify(tab) 之前桶内的所有结点已经变为 TreeNode<K,V>,并且维护着 prev 和 next 地址,因此实际上相当于一条双向链表。有关红黑树的理论知识可以看:红黑树(一)之 原理和算法详细介绍

  将这样的一条链表构造成红黑树的步骤:

  1. 从链表头结点开始往后遍历,将链表的结点改造为红黑树的结点
  2. 设置第一个结点为红黑树的根节点,此后将每个结点与红黑树中的结点从顶至下比较,确定结点在红黑树中的位置
  3. 每次添加一个结点都需要对红黑树进行平衡性调整,因为添加结点可能使得树不再满足红黑树的性质
    /**
     * Forms tree of the nodes linked from this node.
     *
     * @return root of tree
     */
    final void treeify(Node<K, V>[] tab) {
        TreeNode<K, V> root = null;
        // 在每个桶中,是头结点调用的 treeify 方法,因此这里的 this 就是头结点
        for (TreeNode<K, V> x = this, next; x != null; x = next) {
            next = (TreeNode<K, V>) x.next;
            x.left = x.right = null;
            // 如果根节点还是 null,说明 x 是这个红黑树添加的第一个结点
            // 将 root 指向 x,x 作为根节点显然没有父节点,同时根据红黑树的特征,x 应当被标记为黑色
            if (root == null) {
                x.parent = null;
                x.red = false;
                root = x;
            // 不是根结点,就需要查找应当把 x 插入到红黑树的哪个位置了
            } else {
                // 获取要插入结点的 key
                K k = x.key;
                // 获取要插入结点的 value
                int h = x.hash;
                // kc 为 key 的所属的对象
                Class<?> kc = null;
                // 从根节点开始寻找要插入的结点应当插入在红黑树的位置
                for (TreeNode<K, V> p = root; ; ) {
                    int dir, ph;
                    // pk 为当前搜索节点的 key 
                    K pk = p.key;
                    // 如果当前节点的 hash 值大于插入结点的 hash 值,插入结点应当在当前节点的左边
                    if ((ph = p.hash) > h)
                        dir = -1;
                    // 同理,右边。在 HashMap 中的桶的 key 的 hash 值相同,应当会进入最后一个 else 分支中去
                    else if (ph < h)
                        dir = 1;
                    // 如果 key 的对象没有实现 Comparable 接口,comparableClassFor 方法返回 null
                    // 或者实现了 Comparable 接口
                    // 且如果当前节点的 key 和插入结点的 key 类型相同,返回它们的比较结果(compareComparables()方法)
                    // 否则返回 0
                    // 简单理解这个括号内的条件就是判断两个 key 是否能比较,不能比较以及比较结果为 0 ,都再调用一次 tieBreakOrder 方法
                    else if ((kc == null &&
                            (kc = comparableClassFor(k)) == null) ||
                            // 注意这里如果能够比较,比较的值已经赋值给了 dir
                            (dir = compareComparables(kc, k, pk)) == 0)
                        // 如果不能比较,调用 tieBreakOrder
                        // 这个方法主要根据两个 key 的 hashCode 进行比较
                        // 如果两个 key 有一个为 null 或者所属类相同,就按照hashCode比较,当前 key 的哈希值小于等于根节点 key 的哈希值,返回 -1 ,大于返回 1
                        // 否则返回 0
                        dir = tieBreakOrder(k, pk);
                    
                    // xp记录当前结点
                    TreeNode<K, V> xp = p;
                    // 根据 dir 的值判断应当往左子树走还是右子树
                    // 注意此时 p 已经被赋值为它的子树了
                    // 因此如果当前结点的两个子节点都不为空不执行内部的代码
                    // 也会因为循环而继续找下去,直到找到一个有空子结点的结点
                    // 当然找到的空结点的位置仍然要满足dir指定的左右关系
                    if ((p = (dir <= 0) ? p.left : p.right) == null) {
                        // 设置插入结点的父结点为当前结点
                        x.parent = xp;
                        // 根据dir指定的左右关系插入到当前结点的左右子树
                        if (dir <= 0)
                            xp.left = x;
                        else
                            xp.right = x;
                        // 插入后可能破坏了红黑树的规则,要对红黑树进行调整,使得红黑树平衡    
                        root = balanceInsertion(root, x);
                        break;
                    }
                }
            }
        }
        // 构造树完成后,还需要将树的根节点放在table对应的桶内
        // 因为原来链表的头结点不一定是红黑树的根节点
        moveRootToFront(tab, root);
    }

  将红黑树平衡的方法:

    static <K,V> TreeNode<K,V> balanceInsertion(TreeNode<K,V> root,
                                                    TreeNode<K,V> x) {
            // 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> rotateLeft(TreeNode<K,V> root,
                                              TreeNode<K,V> p) {
            // p 为当前结点,r 为右孩子
            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;
        }