JDK8 HashMap--treeify()树形化方法

 1   /*创建红黑树*/
 2     final void treeify(Node<K,V>[] tab) {
 3             TreeNode<K,V> root = null;// 定义红黑树根节点root
 4             for (TreeNode<K,V> x = this, next; x != null; x = next) {// 循环,定义x:循环变量,代表当前节点、next:当前节点的后继元
 5                 next = (TreeNode<K,V>)x.next;
 6                 x.left = x.right = null;// 初始化当前节点x的左子节点、右子节点
 7                 if (root == null) {// 若root为空,表明首次循环此时x指向的节点为根节点
 8                     x.parent = null;// 根节点无父节点
 9                     x.red = false;// 根节点为黑色
10                     root = x;
11                 }
12                 else {// 除首次循环外其余均走这个分支
13                     K k = x.key;// 获取当前节点的key与hash值
14                     int h = x.hash;
15                     Class<?> kc = null;// 定义key的Class对象kc
16                     for (TreeNode<K,V> p = root;;) {// 循环,每次循环从根节点开始,寻找位置
17                         int dir, ph;// 定义节点相对位置、节点p的hash值
18                         K pk = p.key;// 获取节点p的key
19                         if ((ph = p.hash) > h)
20                             dir = -1;// 当前节点在节点p的左子树
21                         else if (ph < h)
22                             dir = 1;// 当前节点在节点p的右子树
23                         else if ((kc == null &&
24                                   (kc = comparableClassFor(k)) == null) ||
25                                  (dir = compareComparables(kc, k, pk)) == 0)
26                             dir = tieBreakOrder(k, pk);// 当前节点与节点p的hash值相等,当前节点key并没有实现Comparable接口或者实现Comparable接口并且与节点pcompareTo相等,该方法是为了保证在特殊情况下节点添加的一致性用于维持红黑树的平衡
27 
28                         TreeNode<K,V> xp = p;
29                         if ((p = (dir <= 0) ? p.left : p.right) == null) {// 根据dir判断添加位置也是节点p的左右节点,是否为空,若不为null在p的子树上进行下次循环
30                             x.parent = xp;// 若添加位置为null,建立当前节点x与父节点xp之间的联系
31                             if (dir <= 0)// 确定当前节点时xp的左节点还是右节点
32                                 xp.left = x;
33                             else
34                                 xp.right = x;
35                             root = balanceInsertion(root, x);// 对红黑是进行平衡操作并结束循环
36                             break;
37                         }
38                     }
39                 }
40             }
41             moveRootToFront(tab, root);// 将红黑树根节点复位至数组头结点
42         }
原文地址:https://www.cnblogs.com/flydoging/p/10384773.html