本章, 我们主要介绍java.util.TreeMap
.
根据上述图片, 其继承关系为TreeMap -> NavigableMap -> SortedMap -> Map
.
同样. 我们从成员变量
和基本方法
进行解读.
private final Comparator super K> comparator;
private transient Entry root;
private transient int size = 0;
private transient int modCount = 0;
public class TreeMap
extends AbstractMap
implements NavigableMap, Cloneable, java.io.Serializable
{
public interface NavigableMap extends SortedMap {
public interface SortedMap extends Map {
Comparator super K> comparator();
public interface Map {
对于TreeMap -> NavigableMap -> SortedMap -> Map
这条继承线. 这边一带而过, Comparator比较器
是在SortedMap
内定义的. 后面有时间再仔细讲解.
static final class Entry implements Map.Entry {
K key;
V value;
Entry left;
Entry right;
Entry parent;
boolean color = BLACK;
}
TreeMap
的数据节点. 可以看出, 其是一个红黑树节点. 除了包括 K/V
之外, 还包括了父指针/左指针/右指针
和节点颜色标记
.
public TreeMap() {
comparator = null;
}
public TreeMap(Comparator super K> comparator) {
this.comparator = comparator;
}
public TreeMap(Map extends K, ? extends V> m) {
comparator = null;
putAll(m);
}
public TreeMap(SortedMap m) {
comparator = m.comparator();
try {
buildFromSorted(m.size(), m.entrySet().iterator(), null, null);
} catch (java.io.IOException cannotHappen) {
} catch (ClassNotFoundException cannotHappen) {
}
}
其构造函数主要包括4种:
public TreeMap()
public TreeMap(Comparator super K> comparator)
public TreeMap(Map extends K, ? extends V> m)
public TreeMap(SortedMap m)
可以看到比较器``
private final Comparator super K> comparator;
public interface Comparator {
int compare(T o1, T o2);
boolean equals(Object obj);
}
比较器内主要需要实现的方法为compare() 方法
与equals()方法
.
关于Comparator
接口, 我们日常使用的时候主要有3种写法. 详情可看Java 之集合排序
public V get(Object key) {
Entry p = getEntry(key);
return (p==null ? null : p.value);
}
final Entry getEntry(Object key) {
// Offload comparator-based version for sake of performance
if (comparator != null)
return getEntryUsingComparator(key);
if (key == null)
throw new NullPointerException();
@SuppressWarnings("unchecked")
Comparable super K> k = (Comparable super K>) key;
Entry p = root;
while (p != null) {
int cmp = k.compareTo(p.key);
if (cmp < 0)
p = p.left;
else if (cmp > 0)
p = p.right;
else
return p;
}
return null;
}
从此处可以看到. 这就是一个二叉排序树的搜索. 从root
节点开始. 如果小于, 则比较左节点; 如果大于, 则比较右节点. 至于为何能这样进行查找, 还是要看其插入和删除节点.
public V put(K key, V value)
public V put(K key, V value) {
Entry t = root;
if (t == null) {
// 没有root节点 & 即没有根节点
compare(key, key); // type (and possibly null) check
root = new Entry<>(key, value, null);
size = 1;
modCount++;
return null;
}
int cmp;
Entry parent;
// split comparator and comparable paths
// 比较器
Comparator super K> cpr = comparator;
if (cpr != null) {
// 有比较器
do {
parent = t;
cmp = cpr.compare(key, t.key);
if (cmp < 0)
t = t.left;
else if (cmp > 0)
t = t.right;
else
// 找到key相同的节点 直接覆盖
return t.setValue(value);
} while (t != null);
}
else {
// 没有比较器 - 使用默认比较器
if (key == null)
throw new NullPointerException();
@SuppressWarnings("unchecked")
Comparable super K> k = (Comparable super K>) key;
do {
parent = t;
cmp = k.compareTo(t.key);
if (cmp < 0)
t = t.left;
else if (cmp > 0)
t = t.right;
else
return t.setValue(value);
} while (t != null);
}
// 创建新节点
Entry e = new Entry<>(key, value, parent);
if (cmp < 0)
parent.left = e;
else
parent.right = e;
// fix即红黑树平衡操作
fixAfterInsertion(e);
size++;
modCount++;
return null;
}
插入操作主要分为如下几种情况:
/** From CLR */
private void fixAfterInsertion(Entry x) {
x.color = RED;
while (x != null && x != root && x.parent.color == RED) {
if (parentOf(x) == leftOf(parentOf(parentOf(x)))) {
Entry y = rightOf(parentOf(parentOf(x)));
if (colorOf(y) == RED) {
setColor(parentOf(x), BLACK);
setColor(y, BLACK);
setColor(parentOf(parentOf(x)), RED);
x = parentOf(parentOf(x));
} else {
if (x == rightOf(parentOf(x))) {
x = parentOf(x);
rotateLeft(x);
}
setColor(parentOf(x), BLACK);
setColor(parentOf(parentOf(x)), RED);
rotateRight(parentOf(parentOf(x)));
}
} else {
Entry y = leftOf(parentOf(parentOf(x)));
if (colorOf(y) == RED) {
setColor(parentOf(x), BLACK);
setColor(y, BLACK);
setColor(parentOf(parentOf(x)), RED);
x = parentOf(parentOf(x));
} else {
if (x == leftOf(parentOf(x))) {
x = parentOf(x);
rotateRight(x);
}
setColor(parentOf(x), BLACK);
setColor(parentOf(parentOf(x)), RED);
rotateLeft(parentOf(parentOf(x)));
}
}
}
root.color = BLACK;
}
public V remove(Object key) {
Entry p = getEntry(key);
if (p == null)
return null;
V oldValue = p.value;
deleteEntry(p);
return oldValue;
}
private void deleteEntry(Entry p) {
modCount++;
size--;
// If strictly internal, copy successor's element to p and then make p
// point to successor.
// 有左右节点
if (p.left != null && p.right != null) {
// 获取中序后续节点
Entry s = successor(p);
p.key = s.key;
p.value = s.value;
p = s;
} // p has 2 children
// Start fixup at replacement node, if it exists.
// 注意 如果之前有左右节点. 前面的更新后 左右子树都是null.
Entry replacement = (p.left != null ? p.left : p.right);
if (replacement != null) {
// Link replacement to parent
replacement.parent = p.parent;
if (p.parent == null)
// 只有一个节点
root = replacement;
else if (p == p.parent.left)
// 只有左节点
p.parent.left = replacement;
else
// 只有右节点
p.parent.right = replacement;
// Null out links so they are OK to use by fixAfterDeletion.
p.left = p.right = p.parent = null;
// Fix replacement
if (p.color == BLACK)
fixAfterDeletion(replacement);
} else if (p.parent == null) { // return if we are the only node.
// 只有一个节点 即根节点
root = null;
} else { // No children. Use self as phantom replacement and unlink.
// 是叶节点
if (p.color == BLACK)
fixAfterDeletion(p);
if (p.parent != null) {
// 更新<叶节点p>的的指针
if (p == p.parent.left)
p.parent.left = null;
else if (p == p.parent.right)
p.parent.right = null;
p.parent = null;
}
}
}
删除的逻辑主要如下所示:
删除的节点为叶子节点:直接删除. 平衡红黑树. (红黑树的特性是叶子节点都是BLACK.
)
删除的节点只有左节点, 或者右节点. 将左或右节点
与父节点
交换. 随后删除.
删除的节点有左右子节点.
中序后续节点
. successor方法
. 即左边最左, 或者右边最右节点. 随后进行替换.parent.left=null
或者parent.right=null
.successor 寻找中序后续节点
/**
* Returns the successor of the specified Entry, or null if no such.
*/
static TreeMap.Entry successor(Entry t) {
if (t == null)
return null;
else if (t.right != null) {
Entry p = t.right;
while (p.left != null)
p = p.left;
return p;
} else {
Entry p = t.parent;
Entry ch = t;
while (p != null && ch == p.right) {
ch = p;
p = p.parent;
}
return p;
}
}
/** From CLR */
private void fixAfterDeletion(Entry x) {
while (x != root && colorOf(x) == BLACK) {
if (x == leftOf(parentOf(x))) {
Entry sib = rightOf(parentOf(x));
if (colorOf(sib) == RED) {
setColor(sib, BLACK);
setColor(parentOf(x), RED);
rotateLeft(parentOf(x));
sib = rightOf(parentOf(x));
}
if (colorOf(leftOf(sib)) == BLACK &&
colorOf(rightOf(sib)) == BLACK) {
setColor(sib, RED);
x = parentOf(x);
} else {
if (colorOf(rightOf(sib)) == BLACK) {
setColor(leftOf(sib), BLACK);
setColor(sib, RED);
rotateRight(sib);
sib = rightOf(parentOf(x));
}
setColor(sib, colorOf(parentOf(x)));
setColor(parentOf(x), BLACK);
setColor(rightOf(sib), BLACK);
rotateLeft(parentOf(x));
x = root;
}
} else { // symmetric
Entry sib = leftOf(parentOf(x));
if (colorOf(sib) == RED) {
setColor(sib, BLACK);
setColor(parentOf(x), RED);
rotateRight(parentOf(x));
sib = leftOf(parentOf(x));
}
if (colorOf(rightOf(sib)) == BLACK &&
colorOf(leftOf(sib)) == BLACK) {
setColor(sib, RED);
x = parentOf(x);
} else {
if (colorOf(leftOf(sib)) == BLACK) {
setColor(rightOf(sib), BLACK);
setColor(sib, RED);
rotateLeft(sib);
sib = leftOf(parentOf(x));
}
setColor(sib, colorOf(parentOf(x)));
setColor(parentOf(x), BLACK);
setColor(leftOf(sib), BLACK);
rotateRight(parentOf(x));
x = root;
}
}
}
setColor(x, BLACK);
}
To be continue.
Map
类型的结构.[1]. JDK1.8源码(十一)——java.util.TreeMap类