美文网首页
3.2. treeify(树化) ------ HashMap

3.2. treeify(树化) ------ HashMap

作者: 第二秒 | 来源:发表于2021-03-06 18:37 被阅读0次
    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;//获取当前节点的key
                        int h = x.hash;//获取当前节点的hash
                        Class<?> kc = null;
                        for (TreeNode<K,V> 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<K,V> 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

          本文链接:https://www.haomeiwen.com/subject/sfkrzftx.html