1 public V put(K key, V value) { 2 //t 表示當前節點,記住這個很重要!先把TreeMap 的根節點root 的引用賦值給當前節點 3 TreeMap.Entry<K,V> t = root; 4 //若是當前節點爲null ,便是空樹,新增的KV 造成的節點就是根節點 5 if (t == null) { 6 //看似畫蛇添足,實際上預檢了Key 是否 能夠比較 7 compare(key, key); // type (and possibly null) check 8 // 使用Kv 構造出新的Entry 對象,其中第三個參數就是parent ,根節點沒有父親節點 9 root = new TreeMap.Entry<>(key, value, null); 10 size = 1; 11 modCount++; 12 return null; 13 } 14 // cmp 用來接收比較結果 15 int cmp; 16 TreeMap.Entry<K,V> parent; 17 // split comparator and comparable paths 18 //構造方法中置入的外部比較器 19 Comparator<? super K> cpr = comparator; 20 // 重點步驟:根據二叉樹的特性,找到新的節點插入的合適位置 21 if (cpr != null) { 22 //循環的目標:根據key 與當前節點key 不斷地進行對比 23 do { 24 //當前節點賦值個父親節點,故從根節點開始遍歷比較 25 parent = t; 26 //比較輸入的參數的key和當前節點Key 的大小 27 cmp = cpr.compare(key, t.key); 28 //參數的key 更小,向左邊走,把當前節點引用移動至它的左子節點上 29 if (cmp < 0) 30 t = t.left; 31 //參數的key 更大,向右邊走,把當前節點引用移動至它的右子節點上 32 else if (cmp > 0) 33 t = t.right; 34 //若是相等,則會殘忍的覆蓋當前節點的Value 值,並返回更新的前的值 35 else 36 return t.setValue(value); 37 } while (t != null); 38 } 39 //在沒有比較器的狀況下,調用天然排序的Comparable 比較 40 else { 41 if (key == null) 42 throw new NullPointerException(); 43 @SuppressWarnings("unchecked") 44 Comparable<? super K> k = (Comparable<? super K>) key; 45 do { 46 parent = t; 47 cmp = k.compareTo(t.key); 48 if (cmp < 0) 49 t = t.left; 50 else if (cmp > 0) 51 t = t.right; 52 else 53 return t.setValue(value); 54 } while (t != null); 55 } 56 // 建立Entry 對象,並把parent 置入參數 57 TreeMap.Entry<K,V> e = new TreeMap.Entry<>(key, value, parent); 58 //新節點找到本身的位置,本來覺得能夠安頓下來---------- 59 if (cmp < 0) 60 //若是比較結果小於0 ,則成爲parent 的左孩子 61 parent.left = e; 62 else 63 //若是比較結果大於0 ,則成爲parent 的右孩子 64 parent.right = e; 65 //還須要從新對這個節點進行着色,旋轉操做,已達到平衡 66 fixAfterInsertion(e); 67 size++; 68 modCount++; 69 //成功插入新節點後,返回null 70 return null; 71 }