之前阅读java7及之前版本HashMap源码时候,没有看全,所以这次决定一个一个方法去看。
先说结论,看完了除TreeNode的部分,红黑树的操作太头疼了(主要是源码很多代码进行了合并之类的,效率高,可读性差),还好我之前看过红黑树,关于红黑的,可以看我的另一个文章 算法导论之第十三章-红黑树
HashMap内部的数据结构
由Node组成的数组table,一般的构造器并不会生成table数组,而是在第一次put时,发现数组不存在,进行resize数组操作时,新建数组,默认16个长度
table每一格保存一个Node,Node为链表格式,如果链表长度过长(大于8时),链表要转化为TreeNode格式,树的格式,是红黑树(较平衡的树,而且保持平衡的代价不是特别高),TreeNode节点变小时,也会转回Node
插入(put):
1、判断是否存在(不存在跳转2、存在直接跳转3)
2、扩容
3、根据(hash&(n-1))的值,判断要插入的位置(n为table的长度),如果插入的位置是空的,直接插入,插入操作结束,如果Node值不为空,判断待插入的值是否和插入位置上的值是否相等(使用equals比较),相等就结束插入,否则进行4
4、如果原位置的Node属于TreeNode,跳转5,否则跳转6
5、在树中边判断是否和节点相等边找寻插入的位置,如果有相等,此次插入结束,否则找到相应位置进行插入,然后进行平衡操作操持树的平衡,跳转7
6、依次判断Node链表里的每个值是否和插入的值相等,如果存在相等的,直接进行结束,否则插入到最后一个节点的后部,插入成功之后,判断链表长度,长度过长,链表转成树,结束之后跳转7
7、确定有新插入的,就要进行size++操作,当size过大时(与threshold进行比较,threshold又与loadFactor有关),要进行扩容操作
获取(get):
1、根据(hash&(n-1))的值,找到table中对应的节点,如果节点为空,直接返回null,如果节点的key和搜索的key一样(euqals比较),直接返回该节点的value,如果节点是TreeNode,执行2,否则,执行3
2、红黑树也是二叉树,递归执行,从根节点开始往下判断,比较hash值,直到找到节点
3、链表就用while循环判断,只是不停next而已
删除(remove):
1、类似get,找到要删除的node,如果node为空,直接结束,不为空,进行判断,如果为树,执行树的删除,执行2,否则执行正常删除,执行3
2、红黑树的删除比较麻烦,在这也说不完,总之就是要保持树的平衡
3、链表的删除就很简单,前后连在一起,那就删除了
4、既然删除了,size–不要忘记
扩容(resize):
1、扩容其实更多是和插入时候才有的,但是毕竟复杂,单列出来。扩容也不一定会扩,如果table的长度够长,那就不会进行扩容,需要扩容时,进行2
2、扩容分为几种,一种是原来是空的,现在建立一个初始数组(一般16个长度),这种情况下,到此就结束了。如果原来数组不为空,那就进行翻倍处理
3、数组长度翻倍,那原来的值就要进行重新加入新的格子里了,如果原位置为空,继续为空,如果原位置就单独Node,直接移动到计算出的新位置,如果是链表,进行4,如果是TreeNode,进行5
4、首先明白一点,hash&(n-1)的计算,会让原来位置在k的节点,重新计算得到k或者k+n。所以我们最后最多也就2个链表,分别移动到新位置就行
5、树的扩容前一步和链表一致的,因为这里的TreeNode保持了链表的特性,有next和pre。分成两个链表之后,如果链表长度大于8,再调用链表转树的方法,那就完成扩容了
线程不安全之处
看到扩容的方法,应该很多人想到了,不安全就在扩容时候。如果两个线程同时插入,线程1扩容,线程2插入,线程1扩容时候遍历数组table,已经遍历完k位置了,这时候线程2把数值插入,线程1扩容结束,线程2的数值只是插入到原table,并没有进入新table。
但是java8有效解决了java7中hashmap的死链问题,因为之前插入时候的值是插入在链表的首位,现在是插入在末尾。
一、构造器
1、无参构造器,只做了一件事,把扩容指数loadFactor设定为默认值0.75(之所以是0.75,后面边看边理解)
public HashMap() {
this.loadFactor = DEFAULT_LOAD_FACTOR; // all other fields defaulted
}
2、带有initialCapacity和loadFactor的构造器。
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))
//大概意思就是怕传入一些奇怪的值,例如:0.0f/0.0f
throw new IllegalArgumentException("Illegal load factor: " +
loadFactor);
this.loadFactor = loadFactor;
//设置需要准备size的大小
this.threshold = tableSizeFor(initialCapacity);
}
/**
* 这个接口的目的就是找到与cap最接近的大于等于cap的且是2的指数的值
* 例如传入5,返回8,传入19返回32
*/
static final int tableSizeFor(int cap) {
int n = cap - 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;
}
3、只带initialCapacity的构造器
public HashMap(int initialCapacity) {
this(initialCapacity, DEFAULT_LOAD_FACTOR);
}
4、传参是Map的构造器
public HashMap(Map<? extends K, ? extends V> m) {
this.loadFactor = DEFAULT_LOAD_FACTOR;
putMapEntries(m, false);
}
//将map值录入到this中
final void putMapEntries(Map<? extends K, ? extends V> m, boolean evict) {
//获取需要插入map的size
int s = m.size();
if (s > 0) {
if (table == null) { // pre-size
//如果table为空
float ft = ((float)s / loadFactor) + 1.0F;
int t = ((ft < (float)MAXIMUM_CAPACITY) ?
(int)ft : MAXIMUM_CAPACITY);
if (t > threshold)
//设置table的数组大小
threshold = tableSizeFor(t);
}
else if (s > threshold)
//扩容操作
resize();
for (Map.Entry<? extends K, ? extends V> e : m.entrySet()) {
K key = e.getKey();
V value = e.getValue();
//把数据录入
putVal(hash(key), key, value, false, evict);
}
}
}
上面代码中的扩容和插入方法,会在后面介绍
二、插入
public V put(K key, V value) {
return putVal(hash(key), key, value, false, true);
}
final V putVal(int hash, K key, V value, boolean onlyIfAbsent,
boolean evict) {
Node<K,V>[] tab; Node<K,V> p; int n, i;
if ((tab = table) == null || (n = tab.length) == 0)
//数组为空时
n = (tab = resize()).length;
if ((p = tab[i = (n - 1) & hash]) == null)
//进行hash计算后的位置上是空的,那就很简单了,直接放到上面去
tab[i] = newNode(hash, key, value, null);
else {
Node<K,V> e; K k;
if (p.hash == hash &&
((k = p.key) == key || (key != null && key.equals(k))))
//已有存在,那就不进行不操作了
e = p;
else if (p instanceof TreeNode)
//如果是树,按树的方法走
e = ((TreeNode<K,V>)p).putTreeVal(this, tab, hash, key, value);
else {
for (int binCount = 0; ; ++binCount) {
if ((e = p.next) == null) {
//把值插入到最后
p.next = newNode(hash, key, value, null);
//次数多于8-1时,将链表转化成树
if (binCount >= TREEIFY_THRESHOLD - 1) // -1 for 1st
treeifyBin(tab, hash);
break;
}
if (e.hash == hash &&
((k = e.key) == key || (key != null && key.equals(k))))
//插入的和链表中某一个key是一样的,就结束循环
break;
p = e;
}
}
if (e != null) { // existing mapping for key
//e!=null表明是并没有插入,因为存在重复
V oldValue = e.value;
if (!onlyIfAbsent || oldValue == null)
e.value = value;
//好像和LinkedHashMap有关
afterNodeAccess(e);
//没有插入插入成功,那就直接返回,不用执行之后的代码了
return oldValue;
}
}
//只是记录下,fail-fast机制需要
++modCount;
if (++size > threshold)
resize();
afterNodeInsertion(evict);
return null;
}
//建树
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);
}
}
三、获取
public V get(Object key) {
Node<K,V> e;
return (e = getNode(hash(key), key)) == null ? null : e.value;
}
final Node<K,V> getNode(int hash, Object key) {
Node<K,V>[] tab; Node<K,V> first, e; int n; K k;
if ((tab = table) != null && (n = tab.length) > 0 &&
(first = tab[(n - 1) & hash]) != null) {
if (first.hash == hash && // always check first node
((k = first.key) == key || (key != null && key.equals(k))))
return first;
if ((e = first.next) != null) {
if (first instanceof TreeNode)
//树的情况去TreeNode执行
return ((TreeNode<K,V>)first).getTreeNode(hash, key);
do {
if (e.hash == hash &&
((k = e.key) == key || (key != null && key.equals(k))))
return e;
} while ((e = e.next) != null);
}
}
return null;
}
四、删除
public V remove(Object key) {
Node<K,V> e;
return (e = removeNode(hash(key), key, null, false, true)) == null ?
null : e.value;
}
public boolean remove(Object key, Object value) {
return removeNode(hash(key), key, value, true, true) != null;
}
final Node<K,V> removeNode(int hash, Object key, Object value,
boolean matchValue, boolean movable) {
Node<K,V>[] tab; Node<K,V> p; int n, index;
if ((tab = table) != null && (n = tab.length) > 0 &&
(p = tab[index = (n - 1) & hash]) != null) {
Node<K,V> node = null, e; K k; V v;
//先找到要删除的节点node
if (p.hash == hash &&
((k = p.key) == key || (key != null && key.equals(k))))
node = p;
else if ((e = p.next) != null) {
if (p instanceof TreeNode)
//树的话去树那查看
node = ((TreeNode<K,V>)p).getTreeNode(hash, key);
else {
do {
if (e.hash == hash &&
((k = e.key) == key ||
(key != null && key.equals(k)))) {
node = e;
break;
}
p = e;
} while ((e = e.next) != null);
}
}
//再进行删除
if (node != null && (!matchValue || (v = node.value) == value ||
(value != null && value.equals(v)))) {
if (node instanceof TreeNode)
//树的删除
((TreeNode<K,V>)node).removeTreeNode(this, tab, movable);
else if (node == p)
//节点为开头
tab[index] = node.next;
else
p.next = node.next;
//只是记录下,fail-fast机制需要
++modCount;
--size;
//同样,和LinkedHashMap有关
afterNodeRemoval(node);
return node;
}
}
return null;
}
五、扩容
//扩容操作
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) {
//老的数组长度已经达到上限,就不再扩容了
threshold = Integer.MAX_VALUE;
return oldTab;
}
else if ((newCap = oldCap << 1) < MAXIMUM_CAPACITY &&
oldCap >= DEFAULT_INITIAL_CAPACITY)
//数组长度*2
newThr = oldThr << 1; // double threshold
}
else if (oldThr > 0) // initial capacity was placed in threshold
//此时原数组是空的,但是原threshold是有的,那就建一个和threshold相等的数组就行
newCap = oldThr;
else { // zero initial threshold signifies using defaults
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;
//如果oldTab为null,那就没有扩容必要,直接给个空数组回去就行
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
//走到这的都是链表
//lo即为low,偏小
Node<K,V> loHead = null, loTail = null;
//hi即为high,偏大
Node<K,V> hiHead = null, hiTail = null;
Node<K,V> next;
do {
//把next取出来
next = e.next;
if ((e.hash & oldCap) == 0) {
//其实这个判断和(e.hash & (newCap - 1))
//这就是在0-(oldCap-1)部分,即插入loHead列表
if (loTail == null)
loHead = e;
else
loTail.next = e;
loTail = e;
}
else {
//这就是在oldCap-(newCap-1)部分,即插入hiHead列表
if (hiTail == null)
hiHead = e;
else
hiTail.next = e;
hiTail = e;
}
//当next一直存在时,进行循环
} while ((e = next) != null);
//下面的操作就是把列表放入table数组中了
if (loTail != null) {
loTail.next = null;
newTab[j] = loHead;
}
if (hiTail != null) {
hiTail.next = null;
newTab[j + oldCap] = hiHead;
}
}
}
}
}
return newTab;
}
六、TreeNodede的方法
1、插入
//TreeNode的put
final TreeNode putTreeVal(HashMap map, Node[] tab,
int h, K k, V v) {
Class> kc = null;
boolean searched = false;
TreeNode root = (parent != null) ? root() : this;
for (TreeNode p = root;;) {
int dir, ph; K pk;
if ((ph = p.hash) > h)
//dir的作用就是判断是走左节点还是右节点
dir = -1;
else if (ph < h)
dir = 1;
else if ((pk = p.key) == k || (k != null && k.equals(pk)))
//重复
return p;
else if ((kc == null &&
(kc = comparableClassFor(k)) == null) ||
(dir = compareComparables(kc, k, pk)) == 0) {
//不能比较,或者比较为0
if (!searched) {
TreeNode 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);
}
TreeNode xp = p;
if ((p = (dir <= 0) ? p.left : p.right) == null) {
//如果要插入的地方是null,那就进行插入,否则进行循环
Node xpn = xp.next;
TreeNode x = map.newTreeNode(h, k, v, xpn);
//将节点放到目标的左边或者右边
if (dir <= 0)
xp.left = x;
else
xp.right = x;
//next和pre的操作,和树没关系,其实只是保持这个树还是链表
xp.next = x;
x.parent = x.prev = xp;
if (xpn != null)
((TreeNode)xpn).prev = x;
//平衡红黑树,然后再检验
moveRootToFront(tab, balanceInsertion(root, x));
return null;
}
}
}
2、扩容
//该方法属于HashMap的内部类TreeNode,树进行扩容
final void split(HashMap map, Node[] tab, int index, int bit) {
//这一步就是准备好要拆开的树
TreeNode b = this;
// Relink into lo and hi lists, preserving order
//很明确,把两个新树准备好
TreeNode loHead = null, loTail = null;
TreeNode hiHead = null, hiTail = null;
int lc = 0, hc = 0;
for (TreeNode e = b, next; e != null; e = next) {
//TreeNode应该还保留了链表的部分特性,有next
next = (TreeNode)e.next;
e.next = null;
if ((e.hash & bit) == 0) {
if ((e.prev = loTail) == null)
loHead = e;
else
//把所有的值都先放入tail中
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) // (else is already treeified)
//那就把链表转成树(上面的操作还是链表)
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);
}
}
}
3、删除
//删除
final void removeTreeNode(HashMap map, Node[] tab,
boolean movable) {
int n;
if (tab == null || (n = tab.length) == 0)
//tab为空
return;
int index = (n - 1) & hash;
TreeNode first = (TreeNode)tab[index], root = first, rl;
TreeNode succ = (TreeNode)next, pred = prev;
//在链表里删除
if (pred == null)
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) {
//我也不知道为啥就这么几个判断,就能得出too small的结论,不过作为较平衡树,如果这样确实too small
//既然too small,那就不要当树了,变回链表吧
tab[index] = first.untreeify(map); // too small
return;
}
TreeNode p = this, pl = left, pr = right, replacement;
if (pl != null && pr != null) {
//左右节点都不为空时
TreeNode s = pr, sl;
//sl是右节点的左节点
while ((sl = s.left) != null) // find successor
s = sl;
//s为(右节点的左节点或者右节点)
//下面三部的操作是交换p和s的颜色
boolean c = s.red;
s.red = p.red;
p.red = c; // swap colors
TreeNode sr = s.right;
TreeNode pp = p.parent;
if (s == pr) { // p was s's direct parent
//如果右节点没有左节点
p.parent = s;
s.right = p;
}
else {
//右节点有左节点
TreeNode sp = s.parent;//sp是p的右节点
if ((p.parent = sp) != null) {
if (s == sp.left)
sp.left = p;
else
sp.right = p;
}
if ((s.right = pr) != null)
pr.parent = s;
}
p.left = null;
if ((p.right = sr) != null)
sr.parent = p;
if ((s.left = pl) != null)
pl.parent = s;
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) {
//下面这个操作,就是把p从树中移除了
TreeNode pp = replacement.parent = p.parent;
if (pp == null)
root = replacement;
else if (p == pp.left)
pp.left = replacement;
else
pp.right = replacement;
p.left = p.right = p.parent = null;
}
//如果p是黑节点,需要进行保持平衡操作
TreeNode r = p.red ? root : balanceDeletion(root, replacement);
if (replacement == p) { // detach
//如果p是叶节点,直接删除
TreeNode pp = p.parent;
p.parent = null;
if (pp != null) {
if (p == pp.left)
pp.left = null;
else if (p == pp.right)
pp.right = null;
}
}
if (movable)
moveRootToFront(tab, r);
}
4、树改链表
//树改成链表代码
final Node untreeify(HashMap map) {
Node hd = null, tl = null;
for (Node q = this; q != null; q = q.next) {
//this现在就是个链表,所以直接转成Node就行
Node p = map.replacementNode(q, null);
if (tl == null)
hd = p;
else
tl.next = p;
tl = p;
}
return hd;
}
5、链表改成树
//链表改成树
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;
int h = x.hash;
Class> kc = null;
for (TreeNode 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 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);
}
6、把root设置为链表的头结点
//确保给定的根是其bin的第一个节点
static void moveRootToFront(Node[] tab, TreeNode root) {
int n;
if (root != null && tab != null && (n = tab.length) > 0) {
int index = (n - 1) & root.hash;
TreeNode first = (TreeNode)tab[index];
if (root != first) {
Node rn;
tab[index] = root;
TreeNode rp = root.prev;
if ((rn = root.next) != null)
((TreeNode)rn).prev = rp;
if (rp != null)
rp.next = rn;
if (first != null)
first.prev = root;
root.next = first;
root.prev = null;
}
assert checkInvariants(root);
}
}
7、搜索
final TreeNode getTreeNode(int h, Object k) {
return ((parent != null) ? root() : this).find(h, k, null);
}
//找位置
final TreeNode find(int h, Object k, Class> kc) {
TreeNode p = this;
do {
int ph, dir; K pk;
TreeNode pl = p.left, pr = p.right, q;
if ((ph = p.hash) > h)
//hash偏小居左
p = pl;
else if (ph < h)
//hash偏大居左
p = pr;
else if ((pk = p.key) == k || (k != null && k.equals(pk)))
//值对了
return p;
else if (pl == null)
//左树空了在判断右树
p = pr;
else if (pr == null)
//右树为空判断左树
p = pl;
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;
}
8、查root
//找root
final TreeNode root() {
for (TreeNode r = this, p;;) {
if ((p = r.parent) == null)
return r;
r = p;
}
}
9、比较内存的hash值
//这是在比较内存地址?
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;
}
10、插入后保持树的平衡
//插入后保持树的平衡
static TreeNode balanceInsertion(TreeNode root,
TreeNode x) {
x.red = true;
for (TreeNode xp, xpp, xppl, xppr;;) {
if ((xp = x.parent) == null) {
x.red = false;
return x;
}
else if (!xp.red || (xpp = xp.parent) == null)
return root;
if (xp == (xppl = xpp.left)) {
if ((xppr = xpp.right) != null && xppr.red) {
xppr.red = false;
xp.red = false;
xpp.red = true;
x = xpp;
}
else {
if (x == xp.right) {
root = rotateLeft(root, x = xp);
xpp = (xp = x.parent) == null ? null : xp.parent;
}
if (xp != null) {
xp.red = false;
if (xpp != null) {
xpp.red = true;
root = rotateRight(root, xpp);
}
}
}
}
else {
if (xppl != null && xppl.red) {
xppl.red = false;
xp.red = false;
xpp.red = true;
x = xpp;
}
else {
if (x == xp.left) {
root = rotateRight(root, x = xp);
xpp = (xp = x.parent) == null ? null : xp.parent;
}
if (xp != null) {
xp.red = false;
if (xpp != null) {
xpp.red = true;
root = rotateLeft(root, xpp);
}
}
}
}
}
}
11、删除后保持树的平衡
//删除后保持树的平衡
static TreeNode balanceDeletion(TreeNode root,
TreeNode x) {
for (TreeNode 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) {
x.red = false;
return root;
}
else if ((xpl = xp.left) == x) {
if ((xpr = xp.right) != null && xpr.red) {
xpr.red = false;
xp.red = true;
root = rotateLeft(root, xp);
xpr = (xp = x.parent) == null ? null : xp.right;
}
if (xpr == null)
x = xp;
else {
TreeNode sl = xpr.left, sr = xpr.right;
if ((sr == null || !sr.red) &&
(sl == null || !sl.red)) {
xpr.red = true;
x = xp;
}
else {
if (sr == null || !sr.red) {
if (sl != null)
sl.red = false;
xpr.red = true;
root = rotateRight(root, xpr);
xpr = (xp = x.parent) == null ?
null : xp.right;
}
if (xpr != null) {
xpr.red = (xp == null) ? false : xp.red;
if ((sr = xpr.right) != null)
sr.red = false;
}
if (xp != null) {
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 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;
}
}
}
}
}
12、左旋
//左旋
static TreeNode rotateLeft(TreeNode root,
TreeNode p) {
TreeNode 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;
else if (pp.left == p)
pp.left = r;
else
pp.right = r;
r.left = p;
p.parent = r;
}
return root;
}
13、右旋
//右旋
static TreeNode rotateRight(TreeNode root,
TreeNode p) {
TreeNode l, pp, lr;
if (p != null && (l = p.left) != null) {
if ((lr = p.left = l.right) != null)
lr.parent = p;
if ((pp = l.parent = p.parent) == null)
(root = l).red = false;
else if (pp.right == p)
pp.right = l;
else
pp.left = l;
l.right = p;
p.parent = l;
}
return root;
}
14、检查树是否正常
//检查树是否正常
static boolean checkInvariants(TreeNode t) {
TreeNode tp = t.parent, tl = t.left, tr = t.right,
tb = t.prev, tn = (TreeNode)t.next;
if (tb != null && tb.next != t)
//t的前节点的后节点不是自己
return false;
if (tn != null && tn.prev != t)
//t的后节点的前节点不是自己
return false;
if (tp != null && t != tp.left && t != tp.right)
//t的父节点的左右节点都不是自己
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;
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;
}
七、其他
//对象是否可比较(这个不是重点,不在这上面花时间了)
static Class> comparableClassFor(Object x) {
if (x instanceof Comparable) {
Class> c; Type[] ts, as; Type t; ParameterizedType p;
if ((c = x.getClass()) == String.class) // bypass checks
return c;
if ((ts = c.getGenericInterfaces()) != null) {
for (int i = 0; i < ts.length; ++i) {
if (((t = ts[i]) instanceof ParameterizedType) &&
((p = (ParameterizedType)t).getRawType() ==
Comparable.class) &&
(as = p.getActualTypeArguments()) != null &&
as.length == 1 && as[0] == c) // type arg is c
return c;
}
}
}
return null;
}
//进行比较
static int compareComparables(Class> kc, Object k, Object x) {
return (x == null || x.getClass() != kc ? 0 :
((Comparable)k).compareTo(x));
}