所使用的jdk版本为1.8.0_172版本,先看一下 TreeMap<K,V> 在JDK中Map的UML类图中的主要继承实现关系:
概述
TreeMap<K,V> 是基于红黑树的实现Navigable接口的Map。TreeMap 根据key的自然顺序(参见 java.lang.Comparable 接口)或者根据创建TreeMap时指定的比较器(java.util.Comparator)进行排序存放键值映射,具体取决于使用的构造方法。
TreeMap 中 containsKey、get、put、remove 的时间复杂度是 log(n) 的。需要注意的是,TreeMap 的实现是不同步的。
数据结构
public class TreeMap<K,V>
extends AbstractMap<K,V>
implements NavigableMap<K,V>, Cloneable, java.io.Serializable
{
/**
* The comparator used to maintain order in this tree map, or
* null if it uses the natural ordering of its keys.
*
* @serial
*/
/**
* 用于维护 TreeMap 中的顺序的比较器,如果使用其键的自然顺序,则 comparator 为null。
*/
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;
红黑树的节点类型 Entry<K,V> :
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 co