前提
jdk1.8之前HashMap的存储方式:链表+hash jdk1.8以后中HashMap的存储方式:链表+hash+红黑树算法
作用
把Node对象转换成TreeNode结构 把链表结构转换成树结构
业务逻辑
1,循环当前链表 1.2,如果是第一个节点,先设置当前对象为根节点 1.3,如果不是根节点,循环当前对象的后面的对象 1.3.1,判断当前子节点是否需要放在左边,还是右边 1.3.2,处理子节点的其他信息,是否为红节点,是否需要旋转(左旋,右旋) 1.4,重置根节点
源码分析
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;
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;
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) ;
}