A Red-Black tree based NavigableMap implementation. The map is sorted according to the Comparable natural ordering of its keys, or by a Comparator provided at map creation time, depending on which constructor is used.
public V get(Object key){
Entry<K,V> p =getEntry(key);return(p==null ? null : p.value);}final Entry<K,V>getEntry(Object key){// Offload comparator-based version for sake of performanceif(comparator != null)returngetEntryUsingComparator(key);if(key == null)thrownewNullPointerException();@SuppressWarnings("unchecked")
Comparable<?super K> k =(Comparable<?super K>) key;
Entry<K,V> p = root;while(p != null){int cmp = k.compareTo(p.key);if(cmp <0)
p = p.left;elseif(cmp >0)
p = p.right;elsereturn p;}return null;}
2.6 remove 操作
remove 方法共分为以下几个步骤:
先和 get 方法类似尝试获取对应键值对
若找不到则直接返回 null
若找到了则先保存对应的值,然后调用 deleteEntry(p)删除该节点并调整红黑树
最后返回保存的值
public V remove(Object key){
Entry<K,V> p =getEntry(key);if(p == null)return null;
V oldValue = p.value;deleteEntry(p);return oldValue;}
2.7 entrySet
TreeMap 遍历是使用的是 EntryIterator 这个内部类
EntryIterator 大多数的实现均在其父类 PrivateEntryIterator 中
PrivateEntryIterator 中的 lastReturned 用于存放返回的节点,在调用 nextEntry 方法获取下一个节点的过程中,使用了 successor 方法