TreeMap
域:

构造方法:


看下节点的结构:

put:
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;
if (cpr != null) {
//比较器不为null的话,通过比较器进行比较寻找插入位置
do {
parent = t;
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 {
//比较器为空的话,通过key的compare方法比较
if (key == null)
throw new NullPointerException();
@SuppressWarnings("unchecked")
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);
}
Entry<K,V> e = new Entry<>(key, value, parent);
//插入树中
if (cmp < 0)
parent.left = e;
else
parent.right = e;
//进行红黑树重平衡
fixAfterInsertion(e);
size++;
modCount++;
return null;
}

浙公网安备 33010602011771号