/**
* 我们前面提到TreeMap是可以自动排序的,默认情况下comparator为null,这个时候按照key的自然顺序进行排
* 序,然而并不是所有情况下都可以直接使用key的自然顺序,有时候我们想让Map的自动排序按照我们自己的规则,
* 这个时候你就需要传递Comparator的实现类
*/
private final Comparator<? super K> comparator;
/**
* TreeMap的存储结构既然是红黑树,那么必然会有唯一的根节点。
*/
private transient Entry<K,V> root;
/**
* Map中key-val对的数量,也即是红黑树中节点Entry的数量
*/
private transient int size = 0;
/**
* 红黑树结构的调整次数
*/
private transient int modCount = 0;
/**
* 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> {
//key,val是存储的原始数据
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;
}
}