概述
TreeMap使用红黑树存储元素,可以保证元素按key值的大小进行遍历。
TreeMap 类的继承结构如下:
可以看出:
public class TreeMap<K,V>
extends AbstractMap<K,V>
implements NavigableMap<K,V>, Cloneable, java.io.Serializable
TreeMap实现了Map、SortedMap、NavigableMap、Cloneable、Serializable等接口。
代码分析
成员变量
/**
* The comparator used to maintain order in this tree map, or
* null if it uses the natural ordering of its keys.
*
* TreeMap 内部的比较器,若为空,则为自然顺序。
*/
private final Comparator<? super K> comparator;
// 根节点,TreeMap没有桶的概念,所有的元素都存储在一颗树中。
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;
构造器
TreeMap 有四个构造器,分别如下:
/**
* 无参构造器。使用 key 的自然顺序排列(key 要实现 Comparable 接口)
*/
public TreeMap() {
comparator = null;
}
/**
* 使用指定的 Comparator(比较器)构造一个空的 TreeMap
*/
public TreeMap(Comparator<? super K> comparator) {
this.comparator = comparator;
}
/**
* 使用给定的 Map 构造一个 TreeMap
*/
public TreeMap(Map<? extends K, ? extends V> m) {
comparator = null;
putAll(m);
}
/**
* 使用给定的 SortedMap 构造一个 TreeMap
*(使用 SortedMap 的顺序)
*/
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) {
}
}
构造方法主要分成两类,一类是使用comparator比较器,一类是key必须实现Comparable接口。
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;
}
先简单学习这些基本信息,常用方法后续学习补充…