TreeMap为一个树形结构的MAP结合
类结构
public class TreeMap<K,V>
extends AbstractMap<K,V>
implements NavigableMap<K,V>, Cloneable, java.io.Serializable
{
}
类属性
//比较器
private final Comparator<? super K> comparator
//Entry
private transient Entry<K,V> root = null;
//数量
private transient int size = 0;
//集合修改次数
private transient int modCount = 0;
构造函数
//保证照添加的key-value对进行排序,实现排序遍历。此时考虑key的自然排序或定制排序
底层使用红黑树
R-B Tree,全称是Red-Black Tree,又称为“红黑树”,它一种特殊的二叉查找树。红黑树的每个节点上都有存储位表示节点的颜色,可以是红(Red)或黑(Black)。
红黑树的特性:
(1)每个节点要么黑色要么红色。
(2)根节点是黑色(因为默认初始化的时候color就是true)。
(3)每个叶子节点(NIL)是黑色。 [注意:这里叶子节点,是指为空(NIL或NULL)的叶子节点!]
(4)如果一个节点是红色的,则它的子节点必须是黑色的。
(5)从一个节点到该节点的子孙节点的所有路径上包含相同数目的黑节点。
参考
https://www.cnblogs.com/skywang12345/p/3624343.html
//初始化了一个空的比较器
public TreeMap() {
comparator = null;
}
public TreeMap(Comparator<? super K> comparator) {
this.comparator = comparator;
}
//核心方法
//获取一个节点
//思路就是由树的根节点开始找,通过比较器判断key在树的左边还是右边;
//正常情况下
final Entry<K,V> getEntry(Object key) {
// Offload comparator-based version for sake of performance
if (comparator != null)
return getEntryUsingComparator(key);
if (key == null)
throw new NullPointerException();
@SuppressWarnings("unchecked")
Comparable<? super K> k = (Comparable<? super K>) key;
Entry<K,V> p = root;
while (p != null) {
int cmp = k.compareTo(p.key);
if (cmp < 0)
p = p.left;
else if (cmp > 0)
p = p.right;
else
return p;
}
return null;
}
//Entry
static final class Entry<K,V> implements Map.Entry<K,V> {
K key;//节点key值
V value;//节点value值
Entry<K,V> left = null;//节点的左边节点
Entry<K,V> right = null;//节点的右边节点
Entry<K,V> parent;//节点的父节点
boolean color = BLACK;//默认值为true
}
private static final boolean RED = false;
private static final boolean BLACK = true;