TreeMap put 操作分析

时间:2023-01-08 17:16:25
 public V put(K key, V value) {
//t 表示当前节点,记住这个很重要!先把TreeMap 的根节点root 的引用赋值给当前节点
TreeMap.Entry<K,V> t = root;
//如果当前节点为null ,即是空树,新增的KV 形成的节点就是根节点
if (t == null) {
//看似多此一举,实际上预检了Key 是否 可以比较
compare(key, key); // type (and possibly null) check
// 使用Kv 构造出新的Entry 对象,其中第三个参数就是parent ,根节点没有父亲节点
root = new TreeMap.Entry<>(key, value, null);
size = 1;
modCount++;
return null;
}
// cmp 用来接收比较结果
int cmp;
TreeMap.Entry<K,V> parent;
// split comparator and comparable paths
//构造方法中置入的外部比较器
Comparator<? super K> cpr = comparator;
// 重点步骤:根据二叉树的特性,找到新的节点插入的合适位置
if (cpr != null) {
//循环的目标:根据key 与当前节点key 不断地进行对比
do {
//当前节点赋值个父亲节点,故从根节点开始遍历比较
parent = t;
//比较输入的参数的key和当前节点Key 的大小
cmp = cpr.compare(key, t.key);
//参数的key 更小,向左边走,把当前节点引用移动至它的左子节点上
if (cmp < 0)
t = t.left;
//参数的key 更大,向右边走,把当前节点引用移动至它的右子节点上
else if (cmp > 0)
t = t.right;
//如果相等,则会残忍的覆盖当前节点的Value 值,并返回更新的前的值
else
return t.setValue(value);
} while (t != null);
}
//在没有比较器的情况下,调用自然排序的Comparable 比较
else {
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 对象,并把parent 置入参数
TreeMap.Entry<K,V> e = new TreeMap.Entry<>(key, value, parent);
//新节点找到自己的位置,原本以为可以安顿下来----------
if (cmp < 0)
//如果比较结果小于0 ,则成为parent 的左孩子
parent.left = e;
else
//如果比较结果大于0 ,则成为parent 的右孩子
parent.right = e;
//还需要重新对这个节点进行着色,旋转操作,已达到平衡
fixAfterInsertion(e);
size++;
modCount++;
//成功插入新节点后,返回null
return null;
}