Java 学习:HashMap

HashMap 底层是基于散列算法实现,散列算法分为散列再探测和拉链式。HashMap 则使用了拉链式的散列算法,并在 JDK 1.8 中引入了红黑树优化过长的链表。

HashMap 的红黑树满足下面条件:

  1.  每个结点非黑即红;
  2.  根结点是黑的;
  3. 每个叶结点(叶结点即指树尾端NIL指针或NULL结点)都是黑的;
  4. 如果一个结点是红的,那么它的两个儿子都是黑的;
  5. 该树是完美黑色平衡的,任意空链接到根结点的路径上的黑链接数量相同。

成员变量:

// 初始化桶容量大小
static final int DEFAULT_INITIAL_CAPACITY = 1 << 4;

// 桶的最大值
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 才会发生转换。
 * 这是为了避免在哈希表建立初期,多个键值对恰好被放入了同一个链表中而导致不必要的转化。
 */
static final int MIN_TREEIFY_CAPACITY = 64;

构造函数:

public HashMap(int initialCapacity, float loadFactor) {
        if (initialCapacity < 0)
            throw new IllegalArgumentException("Illegal initial capacity: " +
                                               initialCapacity);
        if (initialCapacity > MAXIMUM_CAPACITY)
            initialCapacity = MAXIMUM_CAPACITY;
        if (loadFactor <= 0 || Float.isNaN(loadFactor))
            throw new IllegalArgumentException("Illegal load factor: " +
                                               loadFactor);
        this.loadFactor = loadFactor;
        // 容器的大小必须是2的幂
        this.threshold = tableSizeFor(initialCapacity);
    }

/*
* 返回一个比给定整数大且最接近的2的幂次方整数
* 一个数的二进制00000001xxxxxxxx
* n |= n >>> 1 : 000000011xxxxxxx
* n |= n >>> 2 : 00000001111xxxxx
* n |= n >>> 4 : 0000000111111111
* ......
* n + 1 : 0000001000000000
*/
private static final int tableSizeFor(int c) {
    int n = c - 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;
}

接下来看看红黑树的实现过程:

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

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

在插入、获取元素时,都会先重构哈希码,对 hash 值进一步计算:

设计者认为这方法很容易发生碰撞。为什么这么说呢?不妨思考一下,在n - 1为15(0x1111)时,其实散列真正生效的只是低4bit的有效位,当然容易碰撞了。对哈希码重新计算,在 n - 1 为 15 是,上面的情况会存放在 4 个桶里面:0000、0001、0100、0101。

因此,设计者想了一个顾全大局的方法(综合考虑了速度、作用、质量),就是把高16bit和低16bit异或了一下。设计者还解释到因为现在大多数的hashCode的分布已经很不错了,就算是发生了碰撞也用O(logn)的tree去做了。仅仅异或一下,既减少了系统的开销,也不会造成的因为高位没有参与下标的计算(table长度比较小时),从而引起的碰撞。

final TreeNode<K,V> putTreeVal(HashMap<K,V> map, Node<K,V>[] tab,
                               int h, K k, V v) {
    Class<?> kc = null;
    boolean searched = false;
    // 查找红黑树的根节点root
    TreeNode<K,V> root = (parent != null) ? root() : this;
    for (TreeNode<K,V> p = root;;) {
        int dir, ph; K pk;
        // hash值是否大于当前节点,如果是则往右子树查找
        if ((ph = p.hash) > h)
            dir = -1;
        // hash值是否小于当前节点,如果是则往左子树查找
        else if (ph < h)
            dir = 1;
       // 当前节点的key值和查找的key相等,则退出,表明已找到对应的节点
        else if ((pk = p.key) == k || (k != null && k.equals(pk)))
            return p;
        /*
        * 如果两个元素是相同的"实现了Comparable接口",那么使用它们的比较方法排序
        * 如果hash值相等,但是没有实现Comparable接口
        * 或者实现Comparable接口但是两对象相等,则继续调用tieBreakOrder方法继续比较大小
        */
        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);
        }

        /*
        * 只插入树的尾部,再进行局部变换
        * 红黑树的实现步骤:
        * 1、插入节点
        * 2、局部变换
        */
        TreeNode<K,V> xp = p;
        if ((p = (dir <= 0) ? p.left : p.right) == null) {
            // TreeNode既是一个红黑树结构,也是一个双链表结构
            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;
        }
    }
}

/*
* 查找是否存在与待插节点key相等的节点
*/
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;
        // 比较当前节点和查找节点的hash值,大于则往左子树查找
        if ((ph = p.hash) > h)
            p = pl;
        // 小于这往右子树查找
        else if (ph < h)
            p = pr;
        /*
        * hash相等则对比key的值是否equals
        * 注意:只有两个待插节点和当前节点的键key相等才返回,否则继续搜索直到为null
        */
        else if ((pk = p.key) == k || (k != null && k.equals(pk)))
            return p;
        // hash值相等且key不相等则判断左节点是否为null
        else if (pl == null)
            p = pr;
        // hash值相等且key不相等则判断右节点是否为null
        else if (pr == null)
            p = pl;
        // key对象实现了Comparable接口且与当前节点的key不相等
        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;
}

/**
* 用这个方法来比较两个对象,返回值要么大于0,要么小于0,不会为0
* 也就是说这一步一定能确定要插入的节点要么是树的左节点,要么是右节点,不然就无法继续满足二叉树结构了
* 
* 先比较两个对象的类名,类名是字符串对象,就按字符串的比较规则
* 如果两个对象是同一个类型,那么调用本地方法为两个对象生成hashCode值,再进行比较,hashCode相等的话返回-1
*/
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;

}

/*
 * 红黑树插入节点后,需要重新平衡
 * root 当前根节点
 * x 新插入的节点
 * 返回重新平衡后的根节点
 */
static <K,V> TreeNode<K,V> balanceInsertion(TreeNode<K,V> root,
                                            TreeNode<K,V> x) {
    // 带插入结点颜色为red
    x.red = true;
    for (TreeNode<K,V> xp, xpp, xppl, xppr;;) {
        // 待插入结点是根结点
        if ((xp = x.parent) == null) {
            x.red = false;
            return x;
        }

        /*
        * 下面情况退出执行:
        *  1、待插结点插入到根结点下的情况
        *  2、父结点是黑色
        */
        else if (!xp.red || (xpp = xp.parent) == null)
            return root;

        // 待插结点的父节点是左结点的情况
        if (xp == (xppl = xpp.left)) {
            /*
            * 注意:x结点的父结点红色,上面的判断已经排除父结点是黑色的情况
            *
            * 结点颜色转换情况:
            * 1、变换根结点同时把根结点颜色状态变为false;
            * 2、当前x结点的父结点和其兄弟结点都是红色,就转换颜色
            *
            * 待插结点的父结点xp是红色且其兄弟结点xppr也是红色,
            * 则直接修改父结点xp、其兄弟结点xppr、爷爷结点xxp的颜色(L3-1)
            * 
            */
            if ((xppr = xpp.right) != null && xppr.red) {
                xppr.red = false;
                xp.red = false;
                xpp.red = true;
                x = xpp;
            }
            else {
                // 待插结点插入到右子树(L3_2_1)
                if (x == xp.right) {
                    // x结点指向父结点,左旋转
                    root = rotateLeft(root, x = xp);
                    xpp = (xp = x.parent) == null ? null : xp.parent;
                }
                /*
                * 包括两种情况(L3_2_2)
                * 1、待插结点插入到左子树
                * 2、待插结点插入到右子树进行左旋转
                */
                if (xp != null) {
                    xp.red = false;
                    if (xpp != null) {
                        xpp.red = true;
                        // 右旋转
                        root = rotateRight(root, xpp);
                    }
                }
            }
        }
        // 如果父节点是爷爷节点的右孩子(L4_2_1)
        else {
            if (xppl != null && xppl.red) {
                xppl.red = false;
                xp.red = false;
                xpp.red = true;
                x = xpp;
            }
            else {
                // 待插结点插入到左结点(L4_2_1)
                if (x == xp.left) {
                    root = rotateRight(root, x = xp);
                    xpp = (xp = x.parent) == null ? null : xp.parent;
                }
                /*
                * 包括两种情况(L4_2_2):
                * 1、待插结点插入右结点
                * 2、待插结点插入左子点进行右旋
                */
                if (xp != null) {
                    xp.red = false;
                    if (xpp != null) {
                        xpp.red = true;
                        root = rotateLeft(root, xpp);
                    }
                }
            }
        }
    }
}

/*
* 结点p是待插结点的父节点
*/
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;
        // p是左结点,重置p父结点的左结点
        else if (pp.left == p)
            pp.left = r;
        // p是右结点,重置p父结点的右结点
        else
            pp.right = r;
        // 重置待插结点的左结点指向p
        r.left = p;
        // 变换后重置p的parent域
        p.parent = r;
    }
    return root;
}

/*
* 结点p是待插结点的爷爷节点
*/
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) {
        // 变更p与左结点的关系
        if ((lr = p.left = l.right) != null)
            lr.parent = p;
        // p是根结点,则变更根节点为左结点且设置颜色
        if ((pp = l.parent = p.parent) == null)
            (root = l).red = false;
        // p是右结点,变更p父结点的右结点指针
        else if (pp.right == p)
            pp.right = l;
        // p是左结点,变更p父结点的左结点指针
        else
            pp.left = l;
        l.right = p;
        p.parent = l;
    }
    return root;
}

插入一个新结点:

左子树插入的新结点 x 的流程(在右子树插入结点雷同):

插入结点主要是避免破坏红黑树的第 4 个性质,在平衡树的过程中,主要是通过左旋、右旋或者二者结合是树达到平衡的状态。

case 1:父结点是黑色,表明该树已处于平衡状态

case 2:父结点的兄弟结点是红色

调整:父结点设置成黑色、伯父结点设置成黑色、祖父结点设置成红色

case 3:插入的是右结点

调整:对父结点设置左旋 ——> case 4。

case 4:插入的是左结点

调整:处理结点设置为父结点 ——> case 2、case 3、case 4。

(特别标注图片来源:https://blog.csdn.net/weixin_42340670/article/details/80550932

待插结点的父结点和其兄弟结点都为红色:

待插结点的父结点是左结点:

待插结点的父结点是右结点:

插入 SEARCHXMPL、ACEHLMPRSX 过程:

删除树结点:

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)
        // 删除的是第一个结点,则修改first引用指向下一个结点
        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 || root.right == null ||
            (rl = root.left) == null || rl.left == null) {
        // 当树的高度小于3,则释放红黑树
        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; 
        TreeNode<K,V> sr = s.right;
        TreeNode<K,V> pp = p.parent;
        if (s == pr) { 
            /*
            * 删除结点的右子树最没有左结点
            * 删除结点parent指向其右结点
            */
            p.parent = s;
            // 删除结点的右结点的右结点指向删除结点
            s.right = p;
        }
        else {
            // 删除结点的右子树存在左结点
            TreeNode<K,V> sp = s.parent;
            // 修改删除结点的parent指向其右子树最小结点的父结点
            if ((p.parent = sp) != null) {
                if (s == sp.left)
                    // 修改sp结点的左结点引用
                    sp.left = p;
                else
                    // 修改sp结点右结点引用(这里存在疑问)
                    sp.right = p;
            }
            if ((s.right = pr) != null)
                // 修改删除结点的右结点的parent指向s右子树最小结点
                pr.parent = s;
        } 
        // 设置p左结点引用
        p.left = null;
        if ((p.right = sr) != null)
            // 设置sr的parent指向s删除结点
            sr.parent = p;
        // 设置s的左结点指向删除结点的左结点
        if ((s.left = pl) != null)
            // 设置删除结点的左结点执行s
            pl.parent = s;
        // 设置替换结点s的parent引用
        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) {
        /*
        * 存在子结点
        * 修改交替结点parent引用
        */
        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;
        // 设置删除结点left、right、parent引用为null,以便回收
        p.left = p.right = p.parent = null;
    }

    /*
    * 1、删除的是没有子结点的红色结点,树也是处于平衡状态
    * 2、交换结点颜色后删除结点还是红色,树也是处于平衡状态
    * 删除结点是红色说明树已处于平衡状态,否则平衡红黑树
    */
    TreeNode<K,V> r = p.red ? root : balanceDeletion(root, replacement);

    if (replacement == p) {  
        // 删除结点没有子结点的结点
        TreeNode<K,V> pp = p.parent;
        p.parent = null;
        if (pp != null) {
            if (p == pp.left)
                // 删除结点是左结点,设置其父节点的左引用为null
                pp.left = null;
            else if (p == pp.right)
                // 删除结点是右结点,设置其父节点的右引用为null
                pp.right = null;
        }
    }
    if (movable)
        // 更正数组槽的第一个元素引用
        moveRootToFront(tab, r);
}

/*
* x代表需要平衡的节点
*/
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) {
            /*
            * 1、删除的是没有子结点的红色结点
            * 2、交替结点的右结点是红色,则直接变黑色,该树已平衡(A_2_3)
            */ 
            x.red = false;
            return root;
        }
        else if ((xpl = xp.left) == x) {
            /*
            * x结点是左结点
            * x结点的兄弟结点是红结点
            */
            if ((xpr = xp.right) != null && xpr.red) {
                // x的兄弟结点变黑色且x的父结点称为红色结点,左旋(A_4_2)
                xpr.red = false;
                xp.red = true;
                root = rotateLeft(root, xp);
                xpr = (xp = x.parent) == null ? null : xp.right;
            }
            if (xpr == null)
                // 没有兄弟结点,改变x引用(A_5_1)
                x = xp;
            else {
                TreeNode<K,V> sl = xpr.left, sr = xpr.right;
                if ((sr == null || !sr.red) &&
                        (sl == null || !sl.red)) {
                    /*
                    * X的兄弟结点U的左右子结点都是黑色
                    * 把H的兄弟结点U变成红色结点(A_3_2)
                    */
                    xpr.red = true;
                    // 向上继续平衡
                    x = xp;
                }
                else {
                    if (sr == null || !sr.red) {
                        if (sl != null)
                            // xpr左结点变为黑色
                            sl.red = false;
                        // xpr设置为红色结点
                        xpr.red = true;
                        // 右旋(A_1_2)
                        root = rotateRight(root, xpr);
                        xpr = (xp = x.parent) == null ?
                                null : xp.right;
                    }
                    if (xpr != null) {
                        // 设置x兄弟结点与其父节点相同的颜色(存在父结点)(A_1_3)
                        xpr.red = (xp == null) ? false : xp.red;
                        if ((sr = xpr.right) != null)
                            // 设置结点为黑色(A_1_3)
                            sr.red = false;
                    }
                    if (xp != null) {
                        // 把x的父结点置为黑色(A_1_4)
                        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;
                }
            }
        }
    }
}

正在处理的结点为X,要删除的结点是左结点(删除的结点是右结点流程相同):

删除操作(当平衡红黑树操作前,删除结点是红色除外)都是使树处于不平衡的状态,违反了任意空链接到根结点的路径上的黑链接数量相同,也就是某一棵子树少了一条黑链接,通过局部变换来使这棵子树的黑链接数达到平衡状态(通过这棵子树根结点的黑链接数加 1)。

case 1:删除的是红色结点,当前处理的结点是删除节点,树已处于平衡状态,直接删除即可

case 2:删除的是黑色结点,当前处理的结点是删除结点

调整:存在兄弟结点(不存在兄弟结点:把当前处理的结点设置为父结点 p)——> case 4、case 5、case 6、case7。

case 3:删除的是黑色结点,如果当前处理的是红色结点,将该结点设置成黑色

经过处理结点的路径少了一层,不符合第五条性质,需要增加一条黑色的路径。

下面的情况如果 ( 不存在兄弟结点 || 左右侄子结点 ) 则把当前处理结点设置为父结点 p

case 4:兄弟结点为红色

调整:兄弟结点设置黑色、父结点设置红色、左旋 ——> case 5、case 6、case 7。

case 5:兄弟结点为黑色,左侄子 LN 为黑色,右侄子 RN 为黑色

调整:父结点设置成红色,把当前处理结点设置为父结点 p。

case 6:兄弟结点为黑色,左侄子 LN 为红色,右侄子 RN 为黑色

调整:LN设置为黑色、兄弟结点S设置为红色、右旋 ——> case 7。

case 7:兄弟结点为黑色,左侄子 LN 颜色不限制,右侄子 RN 为红色

调整:设置兄弟结点与父结点一样的颜色、LR结点设为黑色、父结点设置成黑色、左旋 ——> 平衡。

红黑树构造成功后,接下来要修改存放该 hash 值的数组槽指向的第一个元素引用:

/*
* 把红黑树根结点设为数组槽的第一个元素
* TreeNode既是一个红黑树结构,也是一个双链表结构
* 这个方法保证红黑树的根节点称为链表的首届点
*
* 红黑树根结点发生变更情况:
* 1、根结点被删除
* 2、旋转
*/
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;
            // 设置根结点的prev指向根结点前一个结点
            if ((rn = root.next) != null)
                ((TreeNode<K,V>)rn).prev = rp;
            // 设置根结点前指针的next指向跟结点的后一个结点
            if (rp != null)
                rp.next = rn;
            //设置旧数组槽的第一个元素结点prev执行根结点
            if (first != null)
                first.prev = root;
            // 设置根结点next执行first
            root.next = first;
            root.prev = null;
        }
        /*
         * 这一步是防御性的编程
         * 校验TreeNode对象是否满足红黑树和双链表的特性
         * 如果这个方法校验不通过:可能是因为用户编程失误,破坏了结构(例如:并发场景下);也可能是TreeNode的实现有问题(这个是理论上的以防万一);
         */
        assert checkInvariants(root);
    }
}

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;
    // 当前结点t前后结点是否发生了变化
    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;
    // 父结点和左右子结点都为red
    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;
}

扩容与初始化:

/*
* 树化改造
* 如果容量小于 MIN_TREEIFY_CAPACITY,只会进行简单的扩容。
* 如果容量大于 MIN_TREEIFY_CAPACITY ,则会进行树化改造
*/
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);
    }
}

/*
* 数组槽的初始化与扩容
* 扩容如果对应的数组槽指向的链表结构发生变化:
* 1、如果是红黑树链表则重构红黑树
* 2、否则重构链表
*/
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) {
        if (oldCap >= MAXIMUM_CAPACITY) {
            // 当数组长度大于最大值(1073741824),设置临界值threshold为Integer.MAX_VALUE
            threshold = Integer.MAX_VALUE;
            return oldTab;
        }
        else if ((newCap = oldCap << 1) < MAXIMUM_CAPACITY &&
                oldCap >= DEFAULT_INITIAL_CAPACITY)
            // 新数组的长度、临界值为原来的两倍
            newThr = oldThr << 1; 
    }
    else if (oldThr > 0) 
        // 数组的长度等于临界值,这种情况出现在创建带参数的HashMap对象
        newCap = oldThr;
    else {    
        // 不带任何参数创建HashMap对象的状态赋值           
        newCap = DEFAULT_INITIAL_CAPACITY;
        newThr = (int)(DEFAULT_LOAD_FACTOR * 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"})
    // 创建新数组
    Node<K,V>[] newTab = (Node<K,V>[])new Node[newCap];
    table = newTab;
    if (oldTab != null) {
        for (int j = 0; j < oldCap; ++j) {  
            // 每个数组槽第一个元素
            Node<K,V> e;
            if ((e = oldTab[j]) != null) {
                oldTab[j] = null;
                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
                    // 存放到原来数组槽的指针
                    Node<K,V> loHead = null, loTail = null;
                    // 存放到新数组槽的指针
                    Node<K,V> hiHead = null, hiTail = null;
                    Node<K,V> next;

                    /*
                    * 因为n的值为数组的长度,且是2的幂次方,所以在&操作的结果只可能是0或者n
                    * 根据这个规则:
                    *   0-->放在新表的相同位置
                    *   n-->放在新表的(n+原来位置)
                    */
                    do {
                        next = e.next;
                        /*
                        * 注意这里是 e.hash & oldCap,不是插入的索引:e.hash & (newCap - 1)
                        * 存放的规律:hash & (n-1),即hash与(n-1)在相同位执行与
                        */
                        if ((e.hash & oldCap) == 0) {
                            // hash和旧数组长度执行&操作为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 split(HashMap<K,V> map, Node<K,V>[] tab, int index, int bit) {
    TreeNode<K,V> b = this;
    // 存放在原来数组槽链表头尾结点
    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) {
            // hash和旧数组长度执行&操作为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)
            // 链表长度<6释放红黑树
            tab[index] = loHead.untreeify(map);
        else {
            tab[index] = loHead;
            if (hiHead != null) 
                // 原链表结构发生改变,重构红黑树
                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);
        }
    }
}

/*
* 重构数组槽指向的红黑树
*/
final void treeify(Node<K,V>[] tab) {
    TreeNode<K,V> root = null;
    // x指向数组槽的第一个元素指针
    for (TreeNode<K,V> x = this, next; x != null; x = next) {
        next = (TreeNode<K,V>)x.next;
        // 重构以x结点为根的子树
        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;
                // dir<=0查找左子树,否则查找右子树
                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);
}

/*
* 返回一个non-TreeNodes的列表,以替换那些与该节点相关联的节点。
*/
final Node<K,V> untreeify(HashMap<K,V> map) {
    // 新链表的头尾结点
    Node<K,V> hd = null, tl = null;
    // q指向数组槽的第一个结点
    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
            // 设置next指针
            tl.next = p;
        // 设置尾结点
        tl = p;
    }
    return hd;
}

扩容桶容量变化(桶容量必须是 2 的幂次方):

  1. 初始化桶容量是 16;
  2. 扩容仅仅对当前桶的大小执行 n << 1 操作,直到达到最大值。

扩容对链表结点重新计算索引:

拉链法实现数组扩容:

e.hash = 10    0000 1010        |   e.hash = 42    0010 1010
   cap = 16    0001 0000        |      cap = 16    0001 0000
     &         0000 0000        |        &         0000 0000
// 元素位置在扩容后存放的索引位置没有改变

e.hash = 26    0001 1010
   cap = 16    0001 0000
     &         0001 0000
// 元素位置在扩容后存放的索引发生了变化:原数组索引+原数组长度

参考文章:

Java HashMap工作原理及实现

数据结构与算法(十四)深入理解红黑树和JDK TreeMap和TreeSet源码分析

红黑树(Red-Black Tree)解析

猜你喜欢

转载自blog.csdn.net/dilixinxixitong2009/article/details/82192066