还是从几个常用的方法如数:
1. public TreeMap() {...}
2. public V put(K key, V value) {...}
3. public V get(Object key) {...}
TreeMap.TreeMap() :
public class TreeMap<K,V> {
public TreeMap() {
comparator = null;
}
public TreeMap(Comparator<? super K> comparator) {
this.comparator = comparator;
}
public TreeMap(Map<? extends K, ? extends V> m) {
comparator = null;
putAll(m);
}
}
TreeMap.put() :
目前不清楚TreeMap内部的二叉树到底是哪一种二叉树, 希望分析完put()以后能够确定TreeMap内部二叉树的结构;
public class TreeMap<K,V> {
public V put(K key, V value) {
Entry<K,V> t = root;
if (t == null) {
compare(key, key);
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) {...}
else {
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;
} 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;
}
}
我们假设在插入元素时, cpr.compare(key, t.key)始终!=0, 并且cmp < 0与 cmp > 0交替进行;
1、插入第一个元素时, root = null, 然后root = Entry;
2、插入第二个元素时, 此时parent = t = root = Entry_01, 进入do...while中, t = t.left => t = null, parent.left = e => Entry02 = e = parent.left;
下图表示连续插入两个元素的过程: