概述
TreeMap实现了SotredMap接口,它是有序的集合。而且是一个红黑树结构,每个key-value都作为一个红黑树的节点。如果在调用TreeMap的构造函数时没有指定比较器,则根据key执行自然排序。这点会在接下来的代码中做说明,如果指定了比较器则按照比较器来进行排序。 (也就是在创建TreeMap时如果没有传入Comparator比较器,那么key就必须实现Comparable接口)
TreeMap传入比较器或者key本身实现可比较接口,除了是满足treeMap树结构的排序功能,同时还有去重的功能。
继承关系
public class TreeMap<K,V>
extends AbstractMap<K,V>
implements NavigableMap<K,V>, Cloneable, java.io.Serializable
//间接实现了SortedMap接口
public interface NavigableMap<K,V> extends SortedMap<K,V>
基本属性
private final Comparator<? super K> comparator;
private transient Entry<K,V> root;
/**
* 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;
数据结构
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;
Entry(K key, V value, Entry<K,V> parent) {
this.key = key;
this.value = value;
this.parent = parent;
}
//重写equals()方法
public boolean equals(Object o) {
if (!(o instanceof Map.Entry))
return false;
Map.Entry<?,?> e = (Map.Entry<?,?>)o;
//两个节点的key相等,value相等,这两个节点才相等
return valEquals(key,e.getKey()) && valEquals(value,e.getValue());
}
重写hashCode()方法
public int hashCode() {
int keyHash = (key==null ? 0 : key.hashCode());
int valueHash = (value==null ? 0 : value.hashCode());
key和vale hash值得异或运算,相同则为零,不同则为1
return keyHash ^ valueHash;
}
public String toString() {
return key + "=" + value;
}
}
构造方法
//构造方法,comparator用键的顺序做比较
public TreeMap() {
comparator = null;
}
//构造方法,提供比较器,用指定比较器排序
public TreeMap(Comparator<? super K> comparator) {
his.comparator = comparator;
}
//将m中的元素转化daoTreeMap中,按照键的顺序做比较排序
public TreeMap(Map<? extends K, ? extends V> m) {
comparator = null;
putAll(m);
}
//构造方法,指定的参数为SortedMap
//采用m的比较器排序
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) {
}
}
TreeMap提供了四个构造方法,实现了方法的重载。无参构造方法中比较器的值为null,采用自然排序的方法,如果指定了比较器则称之为定制排序.
- 自然排序:TreeMap的所有key必须实现Comparable接口,所有的key都是同一个类的对象
- 定制排序:创建TreeMap对象传入了一个Comparator对象,该对象负责对TreeMap中所有的key进行排序,采用定制排序不要求Map的key实现Comparable接口。等下面分析到比较方法的时候在分析这两种比较有何不同。
操作
对于Map来说,使用的最多的就是put()/get()/remove()等方法,下面依次进行分析
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++;
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
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<K,V> e = new Entry<>(key, value, parent);
if (cmp < 0)
parent.left = e;
else
parent.right = e;
fixAfterInsertion(e);
size++;
modCount++;
return null;
}
红黑树是一个更高效的检索二叉树,有如下特点:
- 每个节点只能是红色或者黑色
- 根节点永远是黑色的
- 所有的叶子的子节点都是空节点,并且都是黑色的
- 每个红色节点的两个子节点都是黑色的(不会有两个连续的红色节点)
- 从任一个节点到其子树中每个叶子节点的路径都包含相同数量的黑色节点(叶子节点到根节点的黑色节点数量每条路径都相同)
remove()
删除的逻辑,实际上是以替换的方式做删除,找到继承节点代替该节点,然后将继承节点删除。
- 首先判断改节点是否存在同时存在左右两个子节点,如果同时存在,那么就查询到当前节点的右孩子节点或者右孩子节点的最小左孩子,作为继承节点
- 若当前节点只有一个子节点,那么就用唯一的子节点作为该节点的继承节点即可
- 当前节点的值用继承节点的值替换
- 删除继承节点
- 再进行红黑树的平衡
public V remove(Object key) {
Entry<K,V> p = getEntry(key); //根据key查找节点,并返回该节点
if (p == null)
return null;
V oldValue = p.value; //获取key对应的值
deleteEntry(p); //删除节点
return oldValue; //返回key对应的值
}
final Entry<K,V> getEntry(Object key) {
//根据键寻找节点,有非为两种方式,如果定制了比较器,采用定制排序方式,否则使用自然排序
if (comparator != null)
return getEntryUsingComparator(key); //循环遍历树,寻找和key相等的节点
if (key == null)
throw new NullPointerException();
Comparable<? super K> k = (Comparable<? super K>) key;
Entry<K,V> p = root;
while (p != null) { //循环遍历树,寻找和key相等的节点
int cmp = k.compareTo(p.key);
if (cmp < 0)
p = p.left;
else if (cmp > 0)
p = p.right;
else
return p;
}
return null;
}
//删除节点
private void deleteEntry(Entry<K,V> p) {
modCount++; //记录修改的次数
size--; //数量减1
//当前节点的两个孩子都不为空
if (p.left != null && p.right != null) {
//寻找继承者,继承者为当前节点的右孩子节点或者右孩子节点的最小左孩子
Entry<K,V> s = successor(p);
p.key = s.key; //key - value 的替换 ,并没有替换颜色
p.value = s.value;
p = s; //指向继承者
} // p has 2 children
// Start fixup at replacement node, if it exists.
//开始修复树结构,继承者的左孩子不为空,返回左孩子,否则返回右孩子
//不可能存在左右两个孩子都存在的情况,successor寻找的就是最小节点,它的左孩子节点为null
Entry<K,V> replacement = (p.left != null ? p.left : p.right);
if (replacement != null) {
// Link replacement to parent
//已经被选为继承者,当前拥有的一切放弃,所以将孩子交给爷爷抚养
replacement.parent = p.parent;
//p节点没有父节点,则指向根节点
if (p.parent == null)
root = replacement;
//如果p为左孩子,如果p为左孩子,则将p.parent.left = p.left
else if (p == p.parent.left)
p.parent.left = replacement;
else
p.parent.right = replacement;
//删除p节点到左右分支,和父节点的引用
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;
}
}
}
entrySet()遍历
class EntrySet extends AbstractSet<Map.Entry<K,V>> {
public Iterator<Map.Entry<K,V>> iterator() {
return new EntryIterator(getFirstEntry());
}
final class EntryIterator extends PrivateEntryIterator<Map.Entry<K,V>> {
EntryIterator(Entry<K,V> first) {
super(first);
}
public Map.Entry<K,V> next() {
return nextEntry();
}
}
其他方法
- firstEntry() 返回Map中最小的key
- higherEntry(Object key ) 返回该Map中位于key后一位的key-value
- lowerEntry(Object key ) 返回该Map中唯一key前一位的key-value
- tailMap(Object key , boolean inclusive) 返回该Map的子Map