1.TreeMap的继承关系
继承了AbstractMap抽象类,实现了Map接口;
public class TreeMap<K,V> extends AbstractMap<K,V> implements NavigableMap<K,V>, Cloneable, java.io.Serializable
NavigableMap继承了SortedMap类:
public interface NavigableMap<K,V> extends SortedMap<K,V>
也就是这个类,决定了TreeMap与HashMap的不同:HashMap的key是无序的,TreeMap的key是有序的。
2.TreeMap的数据结构
TreeMap底层采用红黑树的数据结构实现的 。其树节点Entry实现了Map.Entry,采用内部类的方式实现:
static final class Entry<K,V> implements Map.Entry<K,V> {
K key;
V value;
Entry<K,V> left;
Entry<K,V> right;
Entry<K,V> parent;
boolean color = BLACK;
//
}
节点存储了元素的key以及value信息以及父节点,左右子节点,以及红黑颜色。
注意:TreeMap同HashTable一样,key和value都不能为null,且key不可重复,value可以重复。。。。
所谓的红黑树是用了红黑规则,为了维持二叉查找树的平衡性稳定而设计的。
TreeMap属性
private final Comparator<? super K> comparator;
private transient Entry<K,V> root = null;
/**
* The number of entries in the tree
*/
private transient int size = 0;
/**
* The number of structural modifications to the tree.
*/
private transient int modCount = 0;
比较器,红黑树根节点,书中元素个数,保证“fail-fast”的modcount.
TreeMap的构造方法
参考:链接:https://www.jianshu.com/p/07cceede7b03(感谢作者!)
4个构造方法:
构造方法一:
1、默认构造方法会创建一颗空树。
public TreeMap() {
comparator = null;
}
2、默认使用key的自然顺序来构建有序树,所谓自然顺序,意思是key的类型是什么,就采用该类型的compareTo方法来比较大小,决定顺序。例如key为String类型,就会用String类的compareTo方法比对大小,如果是Integer类型,就用Integer的compareTo方法比对。Java自带的基本数据类型及其装箱类型都实现了Comparable接口的compareTo方法。
3.要去key必须事实现Comparable接口,以保证key的有序性。
看下边这段代码:
public class TreeMapTest {
public static void main(String[] args) {
// TODO Auto-generated method stub
Map<String, Integer> map = new TreeMap<>();
map.put("abc",444);
map.put("fff",222);
map.put("aaa", 888);
map.put("bbb", 999);
Set<Entry<String,Integer>> set=map.entrySet();
for(Entry<String,Integer> each:set){
System.out.println(each.getKey()+"::"+each.getValue());
}
}
}
输出:
aaa::888
abc::444
bbb::999
fff::222
输出是按String字典顺序排列的,因为String实现了Comparable接口,自然有compateTo方法。
二:
public TreeMap(Comparator<? super K> comparator) {
this.comparator = comparator;
}
除了用默认比较器,TreeMap还提供了支持外部比较器来初始化构造方法。
三:
public TreeMap(Map<? extends K, ? extends V> m) {
comparator = null;
putAll(m);
}
制定一个Map的TreeMap.
四:
public TreeMap(SortedMap<K, ? extends V> m) {
comparator = m.comparator();
try {
buildFromSorted(m.size(), m.entrySet().iterator(), null, null);
} catch (java.io.IOException cannotHappen) {
} catch (ClassNotFoundException cannotHappen) {
}
}
制定一个SortedMap的TreeMap.
因此,从以上的构造方法中可以看出,要创建一个红黑树实现的TreeMap必须要有一个用于比较大小的比较器,因为只有能够比较大小才能实现红黑树的左孩子<树根<右孩子的特点。
TreeMap的方法
1.put方法实现
public V put(K key, V value) {
Entry<K,V> t = root; //根节点
if (t == null) { 如果根节点为空,则创建一个根节点。
compare(key, key); // type (and possibly null) check
root = new Entry<>(key, value, null);
size = 1;
modCount++; 修改modCount;
return null;
}
int cmp;
Entry<K,V> 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和新插入的key相等的话,则覆盖map的value,返回
return t.setValue(value);
} while (t != null); t为null,即没有要比较的节点了,说明找到该插入的位置。
}
else { 如果没有比较器
if (key == null) 用key时必须实现Comparable接口,且不能为空
throw new NullPointerException();
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<K,V> e = new Entry<>(key, value, parent); 创建新节点对象
if (cmp < 0) 如果新节点key的值小于父节点key的值,则插在父节点的左侧
parent.left = e;
else
parent.right = e; 否则,插在右侧。
fixAfterInsertion(e); // 为了保持红黑性质,调整此树
size++; map元素个数加1
modCount++; 有插入则改变加1
return null;
}
fixAfterInsertion(e); 是插入完成后恢复红黑树性质的操作。
private void fixAfterInsertion(Entry<K,V> x) {
x.color = RED; 新插入的节点设置为红色!
while (x != null && x != root && x.parent.color == RED) {
if (parentOf(x) == leftOf(parentOf(parentOf(x)))) {
Entry<K,V> 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<K,V> 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; // 最后将根节点设置为黑色,不管当前是不是红色,反正根节点必须是黑色
}
private void rotateLeft(Entry<K,V> p) { 对红黑树的节点(x)进行左旋转
if (p != null) {
Entry<K,V> r = p.right;
p.right = r.left;
if (r.left != null)
r.left.parent = p;
r.parent = p.parent;
if (p.parent == null)
root = r;
else if (p.parent.left == p)
p.parent.left = r;
else
p.parent.right = r;
r.left = p;
p.parent = r;
}
}
/** From CLR */
private void rotateRight(Entry<K,V> p) { 对红黑树的节点(x)进行右旋转
if (p != null) {
Entry<K,V> l = p.left;
p.left = l.right;
if (l.right != null) l.right.parent = p;
l.parent = p.parent;
if (p.parent == null)
root = l;
else if (p.parent.right == p)
p.parent.right = l;
else p.parent.left = l;
l.right = p;
p.parent = l;
}
}
2.删除方法remove方法的实现
remove方法要比put更加复杂。从源码来看主要两步:
先以二叉查找树方式删除节点,然后回复红黑树性质。
public V remove(Object key) {
Entry<K,V> p = getEntry(key); 首先根据key查找到对应的节点对象
if (p == null)
return null;
V oldValue = p.value; 记录key对应的value,供返回使用
deleteEntry(p); 删除节点
return oldValue; 返回旧结点value
}
remove通过deleteEntry(方法实现。
private void deleteEntry(Entry<K,V> p) {
modCount++; 改变加1
size--; map大小减1
// If strictly internal, copy successor's element to p and then make p
// point to successor.
if (p.left != null && p.right != null) { 情况一:待删除的节点有两个孩子
Entry<K,V> s = successor(p); 查找p的可替代节点(删除有两个孩子的节点时用到)
p.key = s.key;
p.value = s.value;
p = s;
} // p has 2 children
// Start fixup at replacement node, if it exists.
Entry<K,V> 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) {
if (p == p.parent.left) 情况四:无子节点!
p.parent.left = null;
else if (p == p.parent.right)
p.parent.right = null;
p.parent = null;
}
}
}
故TreeMap删除节点remove分四种情况:
1、树只有根节点:直接删除即可。
2、待删除节点无孩子:直接删除即可。
3、待删除节点只有一个孩子节点:删除后,用孩子节点替换自己即可。
4、待删除节点有两个孩子:删除会复杂点,见下文介绍。(用到前三个方法)
static <K,V> TreeMap.Entry<K,V> successor(Entry<K,V> t) {
if (t == null)
return null;
else if (t.right != null) {
Entry<K,V> p = t.right;
while (p.left != null) 找右子树的最左,即最小节点,用来作替换。。
p = p.left;
return p;
} else {
Entry<K,V> p = t.parent;
Entry<K,V> ch = t;
while (p != null && ch == p.right) {
ch = p;
p = p.parent;
}
return p;
}
}
查找要删除节点的替代节点。
private void fixAfterInsertion(Entry<K,V> x) {
x.color = RED;
while (x != null && x != root && x.parent.color == RED) {
if (parentOf(x) == leftOf(parentOf(parentOf(x)))) {
Entry<K,V> 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<K,V> 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;
}
恢复红黑树的性质。
删除有两个子节点的父节点时:(参考https://www.jianshu.com/p/07cceede7b03)
删除过程:找到节点3右子树中最小的节点2,将3和2节点进行交换,然后删除3节点,3删除后,将原来的4节点变为5节点的子节点。
如果3节点和2节点被替换后,3节点下仍有两个孩子节点,重复利用上述规则删除即可。这种方式的巧妙之处在于,总是将删除的当前节点向叶子节点方向移动,保证最后没有两个孩子节点时就可以执行真正的删除了,而利用右子树的最小节点与自身交换的动作并不会破坏二叉查找树的任何特性。
作者:Misout
链接:https://www.jianshu.com/p/07cceede7b03
3.clear方法:
/**
* 清除所有元素
* The map will be empty after this call returns.
*/
public void clear() {
modCount++;
size = 0;
root = null;
}
4.get()查询方法:
public V get(Object key) {
Entry<K,V> p = getEntry(key);
return (p==null ? null : p. value);
}
final Entry<K,V> getEntry(Object key) {
// Offload comparator-based version for sake of performance
if (comparator != null)
// 如果外部比较器为不为空,就用此比较器,用key作为比较器查询
return getEntryUsingComparator(key);
if (key == null)
throw new NullPointerException();
Comparable<? super K> k = (Comparable<? super K>) key;
// 取得root节点
Entry<K,V> p = root;
// 从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;
}
final Entry<K,V> getEntryUsingComparator(Object key) {
K k = (K) key;
Comparator<? super K> cpr = comparator ;
if (cpr != null) {
Entry<K,V> p = root;
while (p != null) {
int cmp = cpr.compare(k, p.key );
if (cmp < 0)
p = p. left;
else if (cmp > 0)
p = p. right;
else
return p;
}
}
return null;
}