TreeMap
- 基于红黑树实现,可以参考HashMap中的红黑树实现方式
- 通过实现Comparable接口对key进行自然排序,或则创建对象时提供Comparator
- get、remove、put、containsKey方法的时间复杂度都是logN
本文只对TreeMap作一个简单的分析,节点的删除、修改、添加、节点调整等具体操作请参考HashMap中源码
属性及构造:
// TreeMap比较器,如果为null,那么将对key进行自然排序
private final Comparator<? super K> comparator;
// 根结点
private transient Entry<K,V> root;
// Tree中的entry数量
private transient int size = 0;
// 对结构的修改次数
private transient int modCount = 0;
// 无参构造,插入的key必须实现Comparable接口
public TreeMap() {
comparator = null;
}
// 通过指定的comparator来创建新的TreeMap
public TreeMap(Comparator<? super K> comparator) {
this.comparator = comparator;
}
public TreeMap(Map<? extends K, ? extends V> m) {
comparator = null;
putAll(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) {
}
}
插入元素:
public V put(K key, V value) {
Entry<K,V> t = root;
// 如果当前树为null,那么直接将待插入的节点做为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);
}
// 将新节点添加到parent下面
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;
}
移除元素:
public V remove(Object key) {
// 获取key对应的节点
Entry<K,V> p = getEntry(key);
if (p == null)
return null;
V oldValue = p.value;
deleteEntry(p);
return oldValue;
}
// 获取key对应的节点
final Entry<K,V> 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<K,V> p = root;
// 从根结点左右比较,直到找到key的节点
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;
}