3.2. treeify(树化) ------ HashMap 源码解析(JDK1.8)

final void treeify(Node[] tab) {
            TreeNode root = null;
            //
            for (TreeNode x = this, next; x != null; x = next) {
                next = (TreeNode)x.next;
                x.left = x.right = null;
                //拿到根节点
                if (root == null) {
                    x.parent = null;
                    x.red = false;//黑化
                    root = x;
                }
                else {
                    K k = x.key;//获取当前节点的key
                    int h = x.hash;//获取当前节点的hash
                    Class kc = null;
                    for (TreeNode p = root;;) {
                        //dir是插入左右节点的依据,
                        int dir, ph;
                        K pk = p.key;
                        //通过哈希值比较大小来确定如何分左右节点
                        if ((ph = p.hash) > h)
                            dir = -1;
                        else if (ph < h)
                            dir = 1;
                        //如果k的哈希值相等,则用k.compareTo()比较大小
                        else if ((kc == null &&
                                  (kc = comparableClassFor(k)) == null) ||
                                 (dir = compareComparables(kc, k, pk)) == 0)
                            //以上方法依然无比较出p和pk大小(即p和pk相等或无法比较)
                            //则用类名来比较,identityHashCode()进行比较
                            dir = tieBreakOrder(k, pk);
                        /*最终dir = 1 或 dir = -1*/
                        TreeNode xp = p;
                        //根据dir选择左右节点,-1为插入左节点,1右节点
                        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);
        }

你可能感兴趣的:(3.2. treeify(树化) ------ HashMap 源码解析(JDK1.8))