一、TreeSet 和 TreeMap 的概述
① TreeSet 和 TreeMap 的继承结构
② 简述
TreeSet集合类实现了SortedSet接口,SortedSet接口继承了Set接口,Set接口继承了Collection接口。TreeSet集合中的元素无序不可重复,同时具有按照元素大小排序的功能。底层实现是二叉树数据结构,被称为可排序集合!
TreeMap集合类实现了SortedMap接口,SortedMap接口继承了Map接口。TreeMap集合中的元素无序不可重复,同时具有按照元素大小排序的功能。底层实现是二叉树数据结构,被称为可排序集合!
TreeSet集合底层实际上是一个TreeMap集合,放到TreeSet集合中的元素,等同于放到TreeMap集合key部分了。
底层是二叉树的集合,存储元素的过程就是排序的过程,取元素时是按照二叉树的中序遍历,取出元素。这时经过中序遍历取出来的元素就是自动按照大小顺序排列的。
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 = 1;
modCount++;
return null;
}
int cmp;
Entry<K,V> parent;
// split comparator and comparable paths
Comparator<? super K> cpr = comparator;
//cpr是一个构造器,TreeSet集合的有参构造会传一个构造器进来
if (cpr != null) {
//有参构造,参数传了个构造器,走这个分支
do {
parent = t;
//构造器的compare()方法,实现了java.util.Comparator接口
cmp = cpr.compare(key, t.key);
if (cmp < 0)
t = t.left;
else if (cmp > 0)
t = t.right;
else
return t.setValue(value);
} while (t != null);
}
else