千锋教育Java入门全套视频教程(java核心技术,适合java零基础,Java

TreeMap的源码分析
创建对象:
public TreeMap() {
comparator = null;//没有比较器
}
public TreeMap(Comparator<? super K> comparator) {
this.comparator = comparator;//自定义一个比较器--暂存你的比较器
}
public V put(K key, V value) {//如果替换了就把被替换的值返给你
Entry<K,V> t = root;//用t这个临时变量来暂存根节点,第一次根节点为null
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;//定义一个临时存父节点的变量
Comparator<? super K> cpr = comparator;//获取自定义比较器
if (cpr != null) {//有自定义比较器
do {
parent = t;//把根节点给父节点
cmp = cpr.compare(key, t.key);//key是要加入的键 t.key父节点的键
if (cmp < 0)//左边
t = t.left;
else if (cmp > 0)
t = t.right;//右边
else
return t.setValue(value);//如果找到相同的key,替换你的值,并且把你的值返回给调用者
} while (t != null);//只要这个循环结束,parent里面存的就是我要添加节点的父节点
}
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);
}
//parent里面存的父节点,cmp里面存的左边还是右边
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;
}