底层是一个红黑树
每一个节点的构成
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;
}
成员变量
1.外部比较器
private final Comparator<? super K> comparator;
2.根节点的引用
private transient Entry<K,V> root;
3.非空节点的个数
private transient int size = 0;
添加原理
1.从根节点开始比较。
2.添加的过程就是一个构造二叉平衡树的过程,会自动平衡。
3.平衡离不开比较,优先使用外部比较器,如果两种比较器都没有就会抛出异常。