继承关系
1.TreeMap存储K-V键值对,通过红黑树(R-B tree)实现;
2.TreeMap继承了NavigableMap接口,NavigableMap接口继承了SortedMap接口,可支持一系列的导航定位以及导航操作的方法,当然只是提供了接口,需要TreeMap自己去实现;
3.TreeMap实现了Cloneable接口,可被克隆,实现了Serializable接口,可序列化;
4.TreeMap因为是通过红黑树实现,红黑树结构天然支持排序,默认情况下通过Key值的自然顺序进行排序;
基本属性
//使用比较器进行排序
private final Comparator<? super K> comparator;
//红黑树结构的根节点
private transient Entry<K,V> root;
/**
* The number of entries in the tree
* Map中key-val对的数量,也即是红黑树中节点Entry的数量
*/
private transient int size = 0;
/**
* The number of structural modifications to the tree.
* 变化的次数
*/
private transient int modCount = 0;
构造方法和初始化
1.构造一个新的空树映射,使用的自然排序键
public TreeMap() {
comparator = null;
}
2.构造一个新的、空的树图,根据给定的命令比较器排序。
public TreeMap(Comparator<? super K> comparator) {
this.comparator = comparator;
}
3. 构造一个新的树形映射,其中包含与给定映射相同的映射映射,根据其键的自然排序排序。
public TreeMap(Map<? extends K, ? extends V> m) {
comparator = null;
putAll(m);
}
4.一个新的树包含相同的映射和map使用与指定的排序映射相同的顺序
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) {
}
}
Entry介绍(红黑树)
基本属性与构造方法源码
// Red-black mechanics
private static final boolean RED = false;
private static final boolean BLACK = true;
/**
* Node in the Tree. Doubles as a means to pass key-value pairs back to
* user (see 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;
/**
* Make a new cell with given key, value, and parent, and with
* {@code null} child links, and BLACK color.
*/
//构造方法
Entry(K key, V value, Entry<K,V> parent) {
this.key = key;
this.value = value;
this.parent = parent;
}
/**
* Returns the key.
*
* @return the key
*/
public K getKey() {
return key;
}
/**
* Returns the value associated with the key.
*
* @return the value associated with the key
*/
public V getValue() {
return value;
}
/**
* Replaces the value currently associated with the key with the given
* value.
*
* @return the value associated with the key before this method was
* called
*/
//替换旧值
public V setValue(V value) {
V oldValue = this.value;
this.value = value;
return oldValue;
}
public boolean equals(Object o) {
if (!(o instanceof Map.Entry))
return false;
Map.Entry<?,?> e = (Map.Entry<?,?>)o;
return valEquals(key,e.getKey()) && valEquals(value,e.getValue());
}
public int hashCode() {
int keyHash = (key==null ? 0 : key.hashCode());
int valueHash = (value==null ? 0 : value.hashCode());
return keyHash ^ valueHash;
}
public String toString() {
return key + "=" + value;
}
}
就是一些简单的get,set方法,已经定义了基本属性,关联左节点右节点,以及父节点的指针。
结构展示
常用方法
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