//外部比较器
private final Comparator<? super K> comparator;
//红黑树的根节点的引用
private transient Entry<K,V> root = null;
//红黑树中节点的个数
private transient int size = 0;
public TreeMap() {
//没有指定外部比较器,为空
comparator = null;
}
//直接返回节点的数量,说明实现的是size++ 或者size--;
public int size() {
return size;
}
=====================================================================
//一个节点中包含数据
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; //颜色为黑
}
==========================================================================
//添加节点
public V put(K key, V value) {
//定义一个引用,指向红黑树的根节点
Entry<K,V> t = root;
//如果红黑树的根节点root为空,为根节点
if (t == null) {
//需要进行比较
compare(key, key); // type (and possibly null) check
//创建一个新的节点作为根节点
root = new Entry<>(key, value, null);
//第一个节点的话size大小为1
size = 1;
modCount++;
return null;
}
int cmp;
Entry<K,V> parent;
// split comparator and comparable paths
//如果存在外部比较器,就用外部比较器
Comparator<? super K> cpr = comparator;
if (cpr != null) {
do {
parent = t;
//从根节点开始比较
cmp = cpr.compare(key, t.key);
//如果小于红黑树当前节点的值
if (cmp < 0)
//就和左子树的根节点比较
t = t.left;
//如果大于红黑树当前节点的值
else if (cmp > 0)
//和右节点的值进行比较
t = t.right;
else
//找到了相同的key值
return t.setValue(value);
//使用新的value的值覆盖旧的value的值.并返回旧的value的值
} while (t != null);
}
else {
//不存在外部比较器,才使用内部比较器
if (key == null)
throw new NullPointerException();
Comparable<? super K> k = (Comparable<? super K>) key;
do {
parent = t;
cmp = k.compareTo(t.key);
if (cmp < 0)
t = t.left;
else if (cmp > 0)
t = t.right;
else
return t.setValue(value);
} while (t != null);
}
//如果比较到最后也没有发现相同的key值,新增一个节点
Entry<K,V> e = new Entry<>(key, value, parent);
if (cmp < 0)
//小于作为左节点存在
parent.left = e;
else
//否则作为右节点存在
parent.right = e;
//size+1 节点数
size++;
modCount++;
return null;
}
==============================================
public V setValue(V value) {
V oldValue = this.value;
this.value = value;
return oldValue;
}
==========================================
//获取value值
public V get(Object key) {
if (key == null)
return getForNullKey();
Entry<K,V> entry = getEntry(key);
return null == entry ? null : entry.getValue();
}
============================================
final Entry<K,V> getEntry(Object key) {
//计算得到hash码
int hash = (key == null) ? 0 : hash(key);
//进行循环查找
for (Entry<K,V> e = table[indexFor(hash, table.length)];
e != null;
e = e.next) {
Object k;
if (e.hash == hash &&
((k = e.key) == key || (key != null && key.equals(k))))
return e;
}
return null;
}
12-08
4140
08-20