public V put(K key, V value) { Entry<K, V> t = root; if (t == null) { // TBD: // 5045147: (coll) Adding null to an empty TreeSet should // throw NullPointerException // // compare(key, key); // type check root = new Entry<K, V>(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) { 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 { if (key == null) throw new NullPointerException(); 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<K, V>(key, value, parent); if (cmp < 0) parent.left = e; else parent.right = e; fixAfterInsertion(e); size++; modCount++; return null; }
root是这颗红黑树的Entry型节点,主要是比较key,key大的节点成为中心节点的右子节点,key小的成为中心节点的左子节点, fixAfterInsertion(e)方法时在插入后按照以上顺序来修复这棵树,因为插入后可能会形成这种局面:
a
??? b
??? ?? c
修复后:
??? b
a???? c
?
size呢表示树的节点数,也就是key-value mappings数量
?