1、源碼註釋java
/** * TreeMap基於NavigableMap 的一個紅黑樹的實現。TreeMap會根據比較器comparator對鍵值對的key進行比較進行排序,若是沒有比較器就是用key的天然排序進行排序,這取決你用什麼構造器 * TreeMap爲containsKey、get、put和remove操做提供了保證的log(n)時間開銷。 * * TreeMap是非線程安全的,若是多個線程同時訪問TreeMap,那必須在外部進行同步,以避免出現線程安全問題。 * 或者經過SortedMap m = Collections.synchronizedSortedMap(new TreeMap(...));來對TreeMap進行包裝 * * 集合的視圖方法返回的迭代器都是快速失敗的,若是在建立迭代器後,任什麼時候候對TreeMap的結構上的 修改(除非經過迭代器的刪除方法),迭代器將拋出ConcurrentModificationException}。 * 所以,在面對併發修改時,迭代器會快速而乾淨地失敗,而不是在未來某個不肯定的時間冒着任意的、不肯定的行爲的風險。、 * * 全部經過類的方法或者視圖的到的 Map.Entry對不支持Entry.setValue 方法。(可是可使用put更改關聯映射中的映射。) * * * @author Josh Bloch and Doug Lea * @see Map * @see HashMap * @see Hashtable * @see Comparable * @see Comparator * @see Collection * @since 1.2 */ public class TreeMap<K,V> extends AbstractMap<K,V> implements NavigableMap<K,V>, Cloneable, java.io.Serializable { /** * 比較器,用來對TreeMap中的節點進行排序,若是使用key的天然排序comparator就爲null */ private final Comparator<? super K> comparator; /** * 紅黑樹的根節點 */ private transient Entry<K,V> root; /** * 紅黑樹的節點總數 */ private transient int size = 0; /** * 結構化修改的次數 */ private transient int modCount = 0; /** * 默認的構造函數,比較器爲null,說明按照天然排序 */ 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); } /** * 經過SortMap來建立TreeMap,SortMap中的key必須是可比較的,也就是實現了Comparable接口 */ public TreeMap(SortedMap<K, ? extends V> m) { comparator = m.comparator(); try { buildFromSorted(m.size(), m.entrySet().iterator(), null, null); } catch (java.io.IOException cannotHappen) { } catch (ClassNotFoundException cannotHappen) { } } // Query Operations /** * 返回節點總個數 */ public int size() { return size; } /** * 是否包含該key */ public boolean containsKey(Object key) { return getEntry(key) != null; } /** * 是否包含該value,遍歷每一個節點,而後去匹配是否存在該value */ public boolean containsValue(Object value) { for (Entry<K,V> e = getFirstEntry(); e != null; e = successor(e)) if (valEquals(value, e.value)) return true; return false; } /** * 返回key對應的value */ public V get(Object key) { Entry<K,V> p = getEntry(key); return (p==null ? null : p.value); } //獲取比較器 public Comparator<? super K> comparator() { return comparator; } /** * 獲取第一個key,若是TreeMap爲空,則拋出異常 */ public K firstKey() { return key(getFirstEntry()); } /** * 返回最後一個key */ public K lastKey() { return key(getLastEntry()); } /** * 將Map中的全部鍵值對添加到TreeMap中 * 若是當前TreeMap中沒有節點,而且傳入map是SortedMap的實現,而且比較器也同樣,這時候直接將map中的鍵值對拷貝到TreeMap中 * 不然就循環添加鍵值對 */ public void putAll(Map<? extends K, ? extends V> map) { int mapSize = map.size(); if (size==0 && mapSize!=0 && map instanceof SortedMap) { Comparator<?> c = ((SortedMap<?,?>)map).comparator(); if (c == comparator || (c != null && c.equals(comparator))) { ++modCount; try { buildFromSorted(mapSize, map.entrySet().iterator(), null, null); } catch (java.io.IOException cannotHappen) { } catch (ClassNotFoundException cannotHappen) { } return; } } super.putAll(map); } /** * 經過key獲取節點。 */ final Entry<K,V> getEntry(Object key) { // Offload comparator-based version for sake of performance if (comparator != null)//存在比較器就經過比較器來進行查找 return getEntryUsingComparator(key); if (key == null)//既沒有比較器,此時key還爲null就拋出異常 throw new NullPointerException(); @SuppressWarnings("unchecked") Comparable<? super K> k = (Comparable<? super K>) key;//最後看key是不是可比較的,來進行查找 Entry<K,V> p = root; while (p != null) { int cmp = k.compareTo(p.key); if (cmp < 0) p = p.left; else if (cmp > 0) p = p.right; else return p; } return null; } /** * 使用比較器的getEntry版本。從getEntry中分離出來以得到性能。(對於不太依賴於比較器性能的大多數方法,這不值得這樣作,但在這裏是值得的。) */ final Entry<K,V> getEntryUsingComparator(Object key) { @SuppressWarnings("unchecked") K k = (K) key; Comparator<? super K> cpr = comparator; if (cpr != null) { Entry<K,V> p = root; while (p != null) { int cmp = cpr.compare(k, p.key); if (cmp < 0) p = p.left; else if (cmp > 0) p = p.right; else return p; } } return null; } /** * 返回大於等於key的最小的key所對應的節點 */ final Entry<K,V> getCeilingEntry(K key) { Entry<K,V> p = root; while (p != null) { int cmp = compare(key, p.key); if (cmp < 0) {//若是要找的key小於當前節點就往左邊找, if (p.left != null) p = p.left; else return p;//找到左節點都沒有左節點了都沒找到,那麼該節點就是大於key的最小左節點 } else if (cmp > 0) { if (p.right != null) { p = p.right; } else { Entry<K,V> parent = p.parent; Entry<K,V> ch = p; //可以進入這個循環說明當前節點沒有右子節點,而且當前節點是父節點的右子節點,而且當前節點還小於查詢的節點 //這樣就只能找它的父節點來看,一直往上找,直到找到某個節點是其父節點的左節點,那個左節點是大於key的 最小節點 //若是往上找,父節點一直都是其父節點的右節點,直到找到root節點,而後返回null。說明沒有比key大的節點 while (parent != null && ch == parent.right) { ch = parent; parent = parent.parent; } return parent; } } else return p; } return null; } /** * 返回小於等於key的最大的節點 */ final Entry<K,V> getFloorEntry(K key) { Entry<K,V> p = root; while (p != null) { int cmp = compare(key, p.key); if (cmp > 0) {//key大於當前節點就往右邊繼續找 if (p.right != null) p = p.right; else return p;//若是該節點沒有右節點,而且此時key還大於當前節點,說明這個節點就是小於key的最大節點了 } else if (cmp < 0) {//若是key小於當前節點 if (p.left != null) {//若是還有左節點,就繼續往左邊找 p = p.left; } else { //若是當前節點沒有左節點了,那麼只有兩種狀況, //一種是當前節點是整個樹的最小節點,那說明真個樹都沒有小於key的節點了,那麼就找到root節點,返回root的父節點null //另一種的就是當前節點不是整個樹的 最小節點,那麼循環獲取父節點的時候,若是某個節點是父節點的右子節點,說明這個該節點的 父節點就是要找的小於key的最大節點 Entry<K,V> parent = p.parent; Entry<K,V> ch = p; while (parent != null && ch == parent.left) { ch = parent; parent = parent.parent; } return parent; } } else return p;//等於key的節點 } return null; } /** * 返回大於key的最小節點,若是沒有就返回null。和getCeilingEntry同樣,只是沒有等於 */ final Entry<K,V> getHigherEntry(K key) { Entry<K,V> p = root; while (p != null) { int cmp = compare(key, p.key); if (cmp < 0) { if (p.left != null) p = p.left; else return p; } else { if (p.right != null) { p = p.right; } else { Entry<K,V> parent = p.parent; Entry<K,V> ch = p; while (parent != null && ch == parent.right) { ch = parent; parent = parent.parent; } return parent; } } } return null; } /** * 返回小於key的最大節點,沒有就返回null。和getFloorEntry同樣,只是沒有等於 */ final Entry<K,V> getLowerEntry(K key) { Entry<K,V> p = root; while (p != null) { int cmp = compare(key, p.key); if (cmp > 0) { if (p.right != null) p = p.right; else return p; } else { if (p.left != null) { p = p.left; } else { Entry<K,V> parent = p.parent; Entry<K,V> ch = p; while (parent != null && ch == parent.left) { ch = parent; parent = parent.parent; } return parent; } } } return null; } /** * 將鍵值對放入TreeMap中 */ public V put(K key, V value) { Entry<K,V> t = root; if (t == null) {//若是根節點爲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; // split comparator and comparable paths Comparator<? super K> cpr = comparator; if (cpr != null) {//若是有比較器, do {//找到key對應的節點,直接將新的值賦給key 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 {//若是沒有比較器,經過key的自身的比較性來進行比較 if (key == null) throw new NullPointerException(); @SuppressWarnings("unchecked") Comparable<? super K> k = (Comparable<? super K>) key; do {//找到key對應的節點,直接將新的值賦給key 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); }//若是沒有找到key對應的節點,就建立一個新的節點,加在父節點下 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; } /** * 刪除節點 */ public V remove(Object key) { Entry<K,V> p = getEntry(key); if (p == null) return null; V oldValue = p.value; deleteEntry(p); return oldValue; } /** * 清空整個TreeMap */ public void clear() { modCount++; size = 0; root = null; } /** * 淺克隆 */ public Object clone() { TreeMap<?,?> clone; try { clone = (TreeMap<?,?>) super.clone(); } catch (CloneNotSupportedException e) { throw new InternalError(e); } // Put clone into "virgin" state (except for comparator) clone.root = null; clone.size = 0; clone.modCount = 0; clone.entrySet = null; clone.navigableKeySet = null; clone.descendingMap = null; // Initialize clone with our mappings try { clone.buildFromSorted(size, entrySet().iterator(), null, null); } catch (java.io.IOException cannotHappen) { } catch (ClassNotFoundException cannotHappen) { } return clone; } // NavigableMap API methods /** * @since 1.6 返回第一個節點 */ public Map.Entry<K,V> firstEntry() { return exportEntry(getFirstEntry()); } /** * @since 1.6 返回最後一個節點 */ public Map.Entry<K,V> lastEntry() { return exportEntry(getLastEntry()); } /** * @since 1.6 返回並刪除第一個節點 */ public Map.Entry<K,V> pollFirstEntry() { Entry<K,V> p = getFirstEntry(); Map.Entry<K,V> result = exportEntry(p); if (p != null) deleteEntry(p); return result; } /** * @since 1.6 返回並刪除最後一個節點 */ public Map.Entry<K,V> pollLastEntry() { Entry<K,V> p = getLastEntry(); Map.Entry<K,V> result = exportEntry(p); if (p != null) deleteEntry(p); return result; } /** * 返回小於key的最大節點 * @since 1.6 */ public Map.Entry<K,V> lowerEntry(K key) { return exportEntry(getLowerEntry(key)); } /** * 返回小於key的最大的 key * @since 1.6 */ public K lowerKey(K key) { return keyOrNull(getLowerEntry(key)); } /** * 返回小於等於key的最大節點 */ public Map.Entry<K,V> floorEntry(K key) { return exportEntry(getFloorEntry(key)); } /** * 返回小於等於key的最大key * @since 1.6 */ public K floorKey(K key) { return keyOrNull(getFloorEntry(key)); } /** * 返回大於等於key的最小節點 * @since 1.6 */ public Map.Entry<K,V> ceilingEntry(K key) { return exportEntry(getCeilingEntry(key)); } /** * 返回大於等於key的最小key * @since 1.6 */ public K ceilingKey(K key) { return keyOrNull(getCeilingEntry(key)); } /** * 返回大於key的最小節點 * @since 1.6 */ public Map.Entry<K,V> higherEntry(K key) { return exportEntry(getHigherEntry(key)); } /** * 返回大於key的最小key * @since 1.6 */ public K higherKey(K key) { return keyOrNull(getHigherEntry(key)); } // Views /** * 在第一次請求此視圖時,建立這些視圖。視圖是無狀態的,所以沒有理由建立多個視圖。 */ private transient EntrySet entrySet; private transient KeySet<K> navigableKeySet; private transient NavigableMap<K,V> descendingMap; /** * 返回key的Set集合,Set中的key按照升序排列 * Set集合的修改會反饋到TreeMap中,一樣TreeMap的修改也反饋到Set集合上 */ public Set<K> keySet() { return navigableKeySet(); } /** * keySet()方法的實現 * @since 1.6 */ public NavigableSet<K> navigableKeySet() { KeySet<K> nks = navigableKeySet; return (nks != null) ? nks : (navigableKeySet = new KeySet<>(this)); } /** * 返回key的Set集合,Set中的key按照降序排列 * NavigableSet集合的修改會反饋到TreeMap中,一樣TreeMap的修改也反饋到NavigableSet集合上 * @since 1.6 */ public NavigableSet<K> descendingKeySet() { return descendingMap().navigableKeySet(); } /** * 返回TreeMap中全部的value,不會對value去重 * value集合的修改會反饋到TreeMap中,一樣TreeMap的修改也反饋到value集合上 */ public Collection<V> values() { Collection<V> vs = values; if (vs == null) { vs = new Values(); values = vs; } return vs; } /** * 返回鍵值對的集合 */ public Set<Map.Entry<K,V>> entrySet() { EntrySet es = entrySet; return (es != null) ? es : (entrySet = new EntrySet()); } /** * 返回TreeMap的倒序Map * 先看有沒有緩存好的descendingMap,若是沒有就建立一個DescendingSubMap返回並緩存 * @since 1.6 */ public NavigableMap<K, V> descendingMap() { NavigableMap<K, V> km = descendingMap; return (km != null) ? km : (descendingMap = new DescendingSubMap<>(this, true, null, true, true, null, true)); } /** * 返回子視圖,升序排列,對視圖的 修改和對源map的修改都會相互影響對方 */ public NavigableMap<K,V> subMap(K fromKey, boolean fromInclusive, K toKey, boolean toInclusive) { return new AscendingSubMap<>(this, false, fromKey, fromInclusive, false, toKey, toInclusive); } /** * 返回TreeMap中鍵小於toKey的全部節點的視圖,inclusive表示是否能夠等於tokey */ public NavigableMap<K,V> headMap(K toKey, boolean inclusive) { return new AscendingSubMap<>(this, true, null, true, false, toKey, inclusive); } /** * 返回TreeMap中鍵大於fromKey的全部節點的視圖,inclusive表示是否能夠等於fromKey */ public NavigableMap<K,V> tailMap(K fromKey, boolean inclusive) { return new AscendingSubMap<>(this, false, fromKey, inclusive, true, null, true); } /** * 返回TreeMap的一個子視圖,key大於等於formKey小於toKey */ public SortedMap<K,V> subMap(K fromKey, K toKey) { return subMap(fromKey, true, toKey, false); } /** * 返回小於key的節點視圖 */ public SortedMap<K,V> headMap(K toKey) { return headMap(toKey, false); } /** * 返回大於等於key的節點視圖 */ public SortedMap<K,V> tailMap(K fromKey) { return tailMap(fromKey, true); } /** * 替換key和value都匹配的value值 */ @Override public boolean replace(K key, V oldValue, V newValue) { Entry<K,V> p = getEntry(key); if (p!=null && Objects.equals(oldValue, p.value)) { p.value = newValue; return true; } return false; } /** * 替換key的value,並返回舊的value */ @Override public V replace(K key, V value) { Entry<K,V> p = getEntry(key); if (p!=null) { V oldValue = p.value; p.value = value; return oldValue; } return null; } /** * 遍歷TreeMap中的節點並作相關的操做 */ @Override public void forEach(BiConsumer<? super K, ? super V> action) { Objects.requireNonNull(action); int expectedModCount = modCount; for (Entry<K, V> e = getFirstEntry(); e != null; e = successor(e)) { action.accept(e.key, e.value); if (expectedModCount != modCount) { throw new ConcurrentModificationException(); } } } /** * 替換括號中知足條件的鍵值對的值,新的值經過括號中的表達式計算獲得 */ @Override public void replaceAll(BiFunction<? super K, ? super V, ? extends V> function) { Objects.requireNonNull(function); int expectedModCount = modCount; for (Entry<K, V> e = getFirstEntry(); e != null; e = successor(e)) { e.value = function.apply(e.key, e.value); if (expectedModCount != modCount) { throw new ConcurrentModificationException(); } } } // TreeMap的值的視圖 class Values extends AbstractCollection<V> { public Iterator<V> iterator() { return new ValueIterator(getFirstEntry()); } public int size() { return TreeMap.this.size(); } public boolean contains(Object o) { return TreeMap.this.containsValue(o); } public boolean remove(Object o) { for (Entry<K,V> e = getFirstEntry(); e != null; e = successor(e)) { if (valEquals(e.getValue(), o)) { deleteEntry(e); return true; } } return false; } public void clear() { TreeMap.this.clear(); } public Spliterator<V> spliterator() { return new ValueSpliterator<K,V>(TreeMap.this, null, null, 0, -1, 0); } } /** * TreeMap的鍵值對視圖 */ class EntrySet extends AbstractSet<Map.Entry<K,V>> { public Iterator<Map.Entry<K,V>> iterator() { return new EntryIterator(getFirstEntry()); } public boolean contains(Object o) { if (!(o instanceof Map.Entry)) return false; Map.Entry<?,?> entry = (Map.Entry<?,?>) o; Object value = entry.getValue(); Entry<K,V> p = getEntry(entry.getKey()); return p != null && valEquals(p.getValue(), value); } public boolean remove(Object o) { if (!(o instanceof Map.Entry)) return false; Map.Entry<?,?> entry = (Map.Entry<?,?>) o; Object value = entry.getValue(); Entry<K,V> p = getEntry(entry.getKey()); if (p != null && valEquals(p.getValue(), value)) { deleteEntry(p); return true; } return false; } public int size() { return TreeMap.this.size(); } public void clear() { TreeMap.this.clear(); } public Spliterator<Map.Entry<K,V>> spliterator() { return new EntrySpliterator<K,V>(TreeMap.this, null, null, 0, -1, 0); } } /** * 鍵迭代器 */ Iterator<K> keyIterator() { return new KeyIterator(getFirstEntry()); } /** * 反向鍵迭代器 * @return */ Iterator<K> descendingKeyIterator() { return new DescendingKeyIterator(getLastEntry()); } //TreeMap中鍵的視圖 static final class KeySet<E> extends AbstractSet<E> implements NavigableSet<E> { private final NavigableMap<E, ?> m; KeySet(NavigableMap<E,?> map) { m = map; } public Iterator<E> iterator() { if (m instanceof TreeMap) return ((TreeMap<E,?>)m).keyIterator(); else return ((TreeMap.NavigableSubMap<E,?>)m).keyIterator(); } public Iterator<E> descendingIterator() { if (m instanceof TreeMap) return ((TreeMap<E,?>)m).descendingKeyIterator(); else return ((TreeMap.NavigableSubMap<E,?>)m).descendingKeyIterator(); } public int size() { return m.size(); } public boolean isEmpty() { return m.isEmpty(); } public boolean contains(Object o) { return m.containsKey(o); } public void clear() { m.clear(); } public E lower(E e) { return m.lowerKey(e); } public E floor(E e) { return m.floorKey(e); } public E ceiling(E e) { return m.ceilingKey(e); } public E higher(E e) { return m.higherKey(e); } public E first() { return m.firstKey(); } public E last() { return m.lastKey(); } public Comparator<? super E> comparator() { return m.comparator(); } public E pollFirst() { Map.Entry<E,?> e = m.pollFirstEntry(); return (e == null) ? null : e.getKey(); } public E pollLast() { Map.Entry<E,?> e = m.pollLastEntry(); return (e == null) ? null : e.getKey(); } public boolean remove(Object o) { int oldSize = size(); m.remove(o); return size() != oldSize; } public NavigableSet<E> subSet(E fromElement, boolean fromInclusive, E toElement, boolean toInclusive) { return new KeySet<>(m.subMap(fromElement, fromInclusive, toElement, toInclusive)); } public NavigableSet<E> headSet(E toElement, boolean inclusive) { return new KeySet<>(m.headMap(toElement, inclusive)); } public NavigableSet<E> tailSet(E fromElement, boolean inclusive) { return new KeySet<>(m.tailMap(fromElement, inclusive)); } public SortedSet<E> subSet(E fromElement, E toElement) { return subSet(fromElement, true, toElement, false); } public SortedSet<E> headSet(E toElement) { return headSet(toElement, false); } public SortedSet<E> tailSet(E fromElement) { return tailSet(fromElement, true); } public NavigableSet<E> descendingSet() { return new KeySet<>(m.descendingMap()); } public Spliterator<E> spliterator() { return keySpliteratorFor(m); } } /** * 鍵值對迭代器 */ abstract class PrivateEntryIterator<T> implements Iterator<T> { Entry<K,V> next; Entry<K,V> lastReturned; int expectedModCount; PrivateEntryIterator(Entry<K,V> first) { expectedModCount = modCount; lastReturned = null; next = first; } public final boolean hasNext() { return next != null; } final Entry<K,V> nextEntry() { Entry<K,V> e = next; if (e == null) throw new NoSuchElementException(); if (modCount != expectedModCount) throw new ConcurrentModificationException(); next = successor(e); lastReturned = e; return e; } final Entry<K,V> prevEntry() { Entry<K,V> e = next; if (e == null) throw new NoSuchElementException(); if (modCount != expectedModCount) throw new ConcurrentModificationException(); next = predecessor(e); lastReturned = e; return e; } public void remove() { if (lastReturned == null) throw new IllegalStateException(); if (modCount != expectedModCount) throw new ConcurrentModificationException(); // deleted entries are replaced by their successors if (lastReturned.left != null && lastReturned.right != null) next = lastReturned; deleteEntry(lastReturned); expectedModCount = modCount; lastReturned = null; } } final class EntryIterator extends PrivateEntryIterator<Map.Entry<K,V>> { EntryIterator(Entry<K,V> first) { super(first); } public Map.Entry<K,V> next() { return nextEntry(); } } final class ValueIterator extends PrivateEntryIterator<V> { ValueIterator(Entry<K,V> first) { super(first); } public V next() { return nextEntry().value; } } final class KeyIterator extends PrivateEntryIterator<K> { KeyIterator(Entry<K,V> first) { super(first); } public K next() { return nextEntry().key; } } final class DescendingKeyIterator extends PrivateEntryIterator<K> { DescendingKeyIterator(Entry<K,V> first) { super(first); } public K next() { return prevEntry().key; } public void remove() { if (lastReturned == null) throw new IllegalStateException(); if (modCount != expectedModCount) throw new ConcurrentModificationException(); deleteEntry(lastReturned); lastReturned = null; expectedModCount = modCount; } } // Little utilities 一些小工具 /** * 比較兩個對象,若是有比較器就用比較器,沒有就用兩個對象的天然排序進行比較 */ @SuppressWarnings("unchecked") final int compare(Object k1, Object k2) { return comparator==null ? ((Comparable<? super K>)k1).compareTo((K)k2) : comparator.compare((K)k1, (K)k2); } /** * 比較兩個兩個對象是否相等 */ static final boolean valEquals(Object o1, Object o2) { return (o1==null ? o2==null : o1.equals(o2)); } /** * 返回entry的 不可變對象 */ static <K,V> Map.Entry<K,V> exportEntry(TreeMap.Entry<K,V> e) { return (e == null) ? null : new AbstractMap.SimpleImmutableEntry<>(e); } /** * 返回鍵值對的鍵 */ static <K,V> K keyOrNull(TreeMap.Entry<K,V> e) { return (e == null) ? null : e.key; } /** * 返回節點的key,節點爲null則報錯 */ static <K> K key(Entry<K,?> e) { if (e==null) throw new NoSuchElementException(); return e.key; } // SubMaps /** * Dummy value serving as unmatchable fence key for unbounded * SubMapIterators */ private static final Object UNBOUNDED = new Object(); /** * @serial include */ abstract static class NavigableSubMap<K,V> extends AbstractMap<K,V> implements NavigableMap<K,V>, java.io.Serializable { private static final long serialVersionUID = -2102997345730753016L; /** * The backing map. */ final TreeMap<K,V> m; /** * fromStart 是否從第一個節點開始 * lo 開始節點 * loInclusive 是否包含lo節點 * * toEnd 是否到最後一個節點 * hi 結束節點 * hiInclusive 是否包含hi節點 */ final K lo, hi; final boolean fromStart, toEnd; final boolean loInclusive, hiInclusive; NavigableSubMap(TreeMap<K,V> m, boolean fromStart, K lo, boolean loInclusive, boolean toEnd, K hi, boolean hiInclusive) { if (!fromStart && !toEnd) { if (m.compare(lo, hi) > 0) throw new IllegalArgumentException("fromKey > toKey"); } else { if (!fromStart) // type check m.compare(lo, lo); if (!toEnd) m.compare(hi, hi); } this.m = m; this.fromStart = fromStart; this.lo = lo; this.loInclusive = loInclusive; this.toEnd = toEnd; this.hi = hi; this.hiInclusive = hiInclusive; } // internal utilities //判斷key是否小於NavigableSubMap的lo final boolean tooLow(Object key) { if (!fromStart) { int c = m.compare(key, lo); if (c < 0 || (c == 0 && !loInclusive)) return true; } return false; } //判斷key是否大於NavigableSubMap的hi final boolean tooHigh(Object key) { if (!toEnd) { int c = m.compare(key, hi); if (c > 0 || (c == 0 && !hiInclusive)) return true; } return false; } //判斷key是否在NavigableSubMap的範圍之間 final boolean inRange(Object key) { return !tooLow(key) && !tooHigh(key); } //判斷key是否在視圖範圍以內 final boolean inClosedRange(Object key) { return (fromStart || m.compare(key, lo) >= 0) && (toEnd || m.compare(hi, key) >= 0); } //判斷key是否在視圖範圍以內 final boolean inRange(Object key, boolean inclusive) { return inclusive ? inRange(key) : inClosedRange(key); } /* * Absolute versions of relation operations. * Subclasses map to these using like-named "sub" * versions that invert senses for descending maps */ final TreeMap.Entry<K,V> absLowest() { TreeMap.Entry<K,V> e = (fromStart ? m.getFirstEntry() : (loInclusive ? m.getCeilingEntry(lo) : m.getHigherEntry(lo))); return (e == null || tooHigh(e.key)) ? null : e; } final TreeMap.Entry<K,V> absHighest() { TreeMap.Entry<K,V> e = (toEnd ? m.getLastEntry() : (hiInclusive ? m.getFloorEntry(hi) : m.getLowerEntry(hi))); return (e == null || tooLow(e.key)) ? null : e; } final TreeMap.Entry<K,V> absCeiling(K key) { if (tooLow(key)) return absLowest(); TreeMap.Entry<K,V> e = m.getCeilingEntry(key); return (e == null || tooHigh(e.key)) ? null : e; } final TreeMap.Entry<K,V> absHigher(K key) { if (tooLow(key)) return absLowest(); TreeMap.Entry<K,V> e = m.getHigherEntry(key); return (e == null || tooHigh(e.key)) ? null : e; } final TreeMap.Entry<K,V> absFloor(K key) { if (tooHigh(key)) return absHighest(); TreeMap.Entry<K,V> e = m.getFloorEntry(key); return (e == null || tooLow(e.key)) ? null : e; } final TreeMap.Entry<K,V> absLower(K key) { if (tooHigh(key)) return absHighest(); TreeMap.Entry<K,V> e = m.getLowerEntry(key); return (e == null || tooLow(e.key)) ? null : e; } /** Returns the absolute high fence for ascending traversal */ final TreeMap.Entry<K,V> absHighFence() { return (toEnd ? null : (hiInclusive ? m.getHigherEntry(hi) : m.getCeilingEntry(hi))); } /** Return the absolute low fence for descending traversal */ final TreeMap.Entry<K,V> absLowFence() { return (fromStart ? null : (loInclusive ? m.getLowerEntry(lo) : m.getFloorEntry(lo))); } // Abstract methods defined in ascending vs descending classes // These relay to the appropriate absolute versions abstract TreeMap.Entry<K,V> subLowest(); abstract TreeMap.Entry<K,V> subHighest(); abstract TreeMap.Entry<K,V> subCeiling(K key); abstract TreeMap.Entry<K,V> subHigher(K key); abstract TreeMap.Entry<K,V> subFloor(K key); abstract TreeMap.Entry<K,V> subLower(K key); /** Returns ascending iterator from the perspective of this submap */ abstract Iterator<K> keyIterator(); abstract Spliterator<K> keySpliterator(); /** Returns descending iterator from the perspective of this submap */ abstract Iterator<K> descendingKeyIterator(); // public methods public boolean isEmpty() { return (fromStart && toEnd) ? m.isEmpty() : entrySet().isEmpty(); } public int size() { return (fromStart && toEnd) ? m.size() : entrySet().size(); } public final boolean containsKey(Object key) { return inRange(key) && m.containsKey(key); } public final V put(K key, V value) { if (!inRange(key)) throw new IllegalArgumentException("key out of range"); return m.put(key, value); } public final V get(Object key) { return !inRange(key) ? null : m.get(key); } public final V remove(Object key) { return !inRange(key) ? null : m.remove(key); } public final Map.Entry<K,V> ceilingEntry(K key) { return exportEntry(subCeiling(key)); } public final K ceilingKey(K key) { return keyOrNull(subCeiling(key)); } public final Map.Entry<K,V> higherEntry(K key) { return exportEntry(subHigher(key)); } public final K higherKey(K key) { return keyOrNull(subHigher(key)); } public final Map.Entry<K,V> floorEntry(K key) { return exportEntry(subFloor(key)); } public final K floorKey(K key) { return keyOrNull(subFloor(key)); } public final Map.Entry<K,V> lowerEntry(K key) { return exportEntry(subLower(key)); } public final K lowerKey(K key) { return keyOrNull(subLower(key)); } public final K firstKey() { return key(subLowest()); } public final K lastKey() { return key(subHighest()); } public final Map.Entry<K,V> firstEntry() { return exportEntry(subLowest()); } public final Map.Entry<K,V> lastEntry() { return exportEntry(subHighest()); } public final Map.Entry<K,V> pollFirstEntry() { TreeMap.Entry<K,V> e = subLowest(); Map.Entry<K,V> result = exportEntry(e); if (e != null) m.deleteEntry(e); return result; } public final Map.Entry<K,V> pollLastEntry() { TreeMap.Entry<K,V> e = subHighest(); Map.Entry<K,V> result = exportEntry(e); if (e != null) m.deleteEntry(e); return result; } // Views transient NavigableMap<K,V> descendingMapView; transient EntrySetView entrySetView; transient KeySet<K> navigableKeySetView; public final NavigableSet<K> navigableKeySet() { KeySet<K> nksv = navigableKeySetView; return (nksv != null) ? nksv : (navigableKeySetView = new TreeMap.KeySet<>(this)); } public final Set<K> keySet() { return navigableKeySet(); } public NavigableSet<K> descendingKeySet() { return descendingMap().navigableKeySet(); } public final SortedMap<K,V> subMap(K fromKey, K toKey) { return subMap(fromKey, true, toKey, false); } public final SortedMap<K,V> headMap(K toKey) { return headMap(toKey, false); } public final SortedMap<K,V> tailMap(K fromKey) { return tailMap(fromKey, true); } // View classes abstract class EntrySetView extends AbstractSet<Map.Entry<K,V>> { private transient int size = -1, sizeModCount; public int size() { if (fromStart && toEnd) return m.size(); if (size == -1 || sizeModCount != m.modCount) { sizeModCount = m.modCount; size = 0; Iterator<?> i = iterator(); while (i.hasNext()) { size++; i.next(); } } return size; } public boolean isEmpty() { TreeMap.Entry<K,V> n = absLowest(); return n == null || tooHigh(n.key); } public boolean contains(Object o) { if (!(o instanceof Map.Entry)) return false; Map.Entry<?,?> entry = (Map.Entry<?,?>) o; Object key = entry.getKey(); if (!inRange(key)) return false; TreeMap.Entry<?,?> node = m.getEntry(key); return node != null && valEquals(node.getValue(), entry.getValue()); } public boolean remove(Object o) { if (!(o instanceof Map.Entry)) return false; Map.Entry<?,?> entry = (Map.Entry<?,?>) o; Object key = entry.getKey(); if (!inRange(key)) return false; TreeMap.Entry<K,V> node = m.getEntry(key); if (node!=null && valEquals(node.getValue(), entry.getValue())) { m.deleteEntry(node); return true; } return false; } } /** * Iterators for SubMaps * 視圖迭代器 */ abstract class SubMapIterator<T> implements Iterator<T> { TreeMap.Entry<K,V> lastReturned; TreeMap.Entry<K,V> next; final Object fenceKey; int expectedModCount; SubMapIterator(TreeMap.Entry<K,V> first, TreeMap.Entry<K,V> fence) { expectedModCount = m.modCount; lastReturned = null; next = first; fenceKey = fence == null ? UNBOUNDED : fence.key; } public final boolean hasNext() { return next != null && next.key != fenceKey; } final TreeMap.Entry<K,V> nextEntry() { TreeMap.Entry<K,V> e = next; if (e == null || e.key == fenceKey) throw new NoSuchElementException(); if (m.modCount != expectedModCount) throw new ConcurrentModificationException(); next = successor(e); lastReturned = e; return e; } final TreeMap.Entry<K,V> prevEntry() { TreeMap.Entry<K,V> e = next; if (e == null || e.key == fenceKey) throw new NoSuchElementException(); if (m.modCount != expectedModCount) throw new ConcurrentModificationException(); next = predecessor(e); lastReturned = e; return e; } final void removeAscending() { if (lastReturned == null) throw new IllegalStateException(); if (m.modCount != expectedModCount) throw new ConcurrentModificationException(); // deleted entries are replaced by their successors if (lastReturned.left != null && lastReturned.right != null) next = lastReturned; m.deleteEntry(lastReturned); lastReturned = null; expectedModCount = m.modCount; } final void removeDescending() { if (lastReturned == null) throw new IllegalStateException(); if (m.modCount != expectedModCount) throw new ConcurrentModificationException(); m.deleteEntry(lastReturned); lastReturned = null; expectedModCount = m.modCount; } } //視圖Entry迭代器 final class SubMapEntryIterator extends SubMapIterator<Map.Entry<K,V>> { SubMapEntryIterator(TreeMap.Entry<K,V> first, TreeMap.Entry<K,V> fence) { super(first, fence); } public Map.Entry<K,V> next() { return nextEntry(); } public void remove() { removeAscending(); } } //逆序視圖entry迭代器 final class DescendingSubMapEntryIterator extends SubMapIterator<Map.Entry<K,V>> { DescendingSubMapEntryIterator(TreeMap.Entry<K,V> last, TreeMap.Entry<K,V> fence) { super(last, fence); } public Map.Entry<K,V> next() { return prevEntry(); } public void remove() { removeDescending(); } } // 簡單實現Spliterator來做爲KeySpliterator的備份 final class SubMapKeyIterator extends SubMapIterator<K> implements Spliterator<K> { SubMapKeyIterator(TreeMap.Entry<K,V> first, TreeMap.Entry<K,V> fence) { super(first, fence); } public K next() { return nextEntry().key; } public void remove() { removeAscending(); } public Spliterator<K> trySplit() { return null; } public void forEachRemaining(Consumer<? super K> action) { while (hasNext()) action.accept(next()); } public boolean tryAdvance(Consumer<? super K> action) { if (hasNext()) { action.accept(next()); return true; } return false; } public long estimateSize() { return Long.MAX_VALUE; } public int characteristics() { return Spliterator.DISTINCT | Spliterator.ORDERED | Spliterator.SORTED; } public final Comparator<? super K> getComparator() { return NavigableSubMap.this.comparator(); } } //逆序視圖key迭代器 final class DescendingSubMapKeyIterator extends SubMapIterator<K> implements Spliterator<K> { DescendingSubMapKeyIterator(TreeMap.Entry<K,V> last, TreeMap.Entry<K,V> fence) { super(last, fence); } public K next() { return prevEntry().key; } public void remove() { removeDescending(); } public Spliterator<K> trySplit() { return null; } public void forEachRemaining(Consumer<? super K> action) { while (hasNext()) action.accept(next()); } public boolean tryAdvance(Consumer<? super K> action) { if (hasNext()) { action.accept(next()); return true; } return false; } public long estimateSize() { return Long.MAX_VALUE; } public int characteristics() { return Spliterator.DISTINCT | Spliterator.ORDERED; } } } /** * 正序視圖 */ static final class AscendingSubMap<K,V> extends NavigableSubMap<K,V> { private static final long serialVersionUID = 912986545866124060L; AscendingSubMap(TreeMap<K,V> m, boolean fromStart, K lo, boolean loInclusive, boolean toEnd, K hi, boolean hiInclusive) { super(m, fromStart, lo, loInclusive, toEnd, hi, hiInclusive); } public Comparator<? super K> comparator() { return m.comparator(); } public NavigableMap<K,V> subMap(K fromKey, boolean fromInclusive, K toKey, boolean toInclusive) { if (!inRange(fromKey, fromInclusive)) throw new IllegalArgumentException("fromKey out of range"); if (!inRange(toKey, toInclusive)) throw new IllegalArgumentException("toKey out of range"); return new AscendingSubMap<>(m, false, fromKey, fromInclusive, false, toKey, toInclusive); } public NavigableMap<K,V> headMap(K toKey, boolean inclusive) { if (!inRange(toKey, inclusive)) throw new IllegalArgumentException("toKey out of range"); return new AscendingSubMap<>(m, fromStart, lo, loInclusive, false, toKey, inclusive); } public NavigableMap<K,V> tailMap(K fromKey, boolean inclusive) { if (!inRange(fromKey, inclusive)) throw new IllegalArgumentException("fromKey out of range"); return new AscendingSubMap<>(m, false, fromKey, inclusive, toEnd, hi, hiInclusive); } public NavigableMap<K,V> descendingMap() { NavigableMap<K,V> mv = descendingMapView; return (mv != null) ? mv : (descendingMapView = new DescendingSubMap<>(m, fromStart, lo, loInclusive, toEnd, hi, hiInclusive)); } Iterator<K> keyIterator() { return new SubMapKeyIterator(absLowest(), absHighFence()); } Spliterator<K> keySpliterator() { return new SubMapKeyIterator(absLowest(), absHighFence()); } Iterator<K> descendingKeyIterator() { return new DescendingSubMapKeyIterator(absHighest(), absLowFence()); } final class AscendingEntrySetView extends EntrySetView { public Iterator<Map.Entry<K,V>> iterator() { return new SubMapEntryIterator(absLowest(), absHighFence()); } } public Set<Map.Entry<K,V>> entrySet() { EntrySetView es = entrySetView; return (es != null) ? es : (entrySetView = new AscendingEntrySetView()); } TreeMap.Entry<K,V> subLowest() { return absLowest(); } TreeMap.Entry<K,V> subHighest() { return absHighest(); } TreeMap.Entry<K,V> subCeiling(K key) { return absCeiling(key); } TreeMap.Entry<K,V> subHigher(K key) { return absHigher(key); } TreeMap.Entry<K,V> subFloor(K key) { return absFloor(key); } TreeMap.Entry<K,V> subLower(K key) { return absLower(key); } } /** * 逆序視圖 */ static final class DescendingSubMap<K,V> extends NavigableSubMap<K,V> { private static final long serialVersionUID = 912986545866120460L; DescendingSubMap(TreeMap<K,V> m, boolean fromStart, K lo, boolean loInclusive, boolean toEnd, K hi, boolean hiInclusive) { super(m, fromStart, lo, loInclusive, toEnd, hi, hiInclusive); } private final Comparator<? super K> reverseComparator = Collections.reverseOrder(m.comparator); public Comparator<? super K> comparator() { return reverseComparator; } public NavigableMap<K,V> subMap(K fromKey, boolean fromInclusive, K toKey, boolean toInclusive) { if (!inRange(fromKey, fromInclusive)) throw new IllegalArgumentException("fromKey out of range"); if (!inRange(toKey, toInclusive)) throw new IllegalArgumentException("toKey out of range"); return new DescendingSubMap<>(m, false, toKey, toInclusive, false, fromKey, fromInclusive); } public NavigableMap<K,V> headMap(K toKey, boolean inclusive) { if (!inRange(toKey, inclusive)) throw new IllegalArgumentException("toKey out of range"); return new DescendingSubMap<>(m, false, toKey, inclusive, toEnd, hi, hiInclusive); } public NavigableMap<K,V> tailMap(K fromKey, boolean inclusive) { if (!inRange(fromKey, inclusive)) throw new IllegalArgumentException("fromKey out of range"); return new DescendingSubMap<>(m, fromStart, lo, loInclusive, false, fromKey, inclusive); } public NavigableMap<K,V> descendingMap() { NavigableMap<K,V> mv = descendingMapView; return (mv != null) ? mv : (descendingMapView = new AscendingSubMap<>(m, fromStart, lo, loInclusive, toEnd, hi, hiInclusive)); } Iterator<K> keyIterator() { return new DescendingSubMapKeyIterator(absHighest(), absLowFence()); } Spliterator<K> keySpliterator() { return new DescendingSubMapKeyIterator(absHighest(), absLowFence()); } Iterator<K> descendingKeyIterator() { return new SubMapKeyIterator(absLowest(), absHighFence()); } final class DescendingEntrySetView extends EntrySetView { public Iterator<Map.Entry<K,V>> iterator() { return new DescendingSubMapEntryIterator(absHighest(), absLowFence()); } } public Set<Map.Entry<K,V>> entrySet() { EntrySetView es = entrySetView; return (es != null) ? es : (entrySetView = new DescendingEntrySetView()); } TreeMap.Entry<K,V> subLowest() { return absHighest(); } TreeMap.Entry<K,V> subHighest() { return absLowest(); } TreeMap.Entry<K,V> subCeiling(K key) { return absFloor(key); } TreeMap.Entry<K,V> subHigher(K key) { return absLower(key); } TreeMap.Entry<K,V> subFloor(K key) { return absCeiling(key); } TreeMap.Entry<K,V> subLower(K key) { return absHigher(key); } } /** * 視圖, */ private class SubMap extends AbstractMap<K,V> implements SortedMap<K,V>, java.io.Serializable { private static final long serialVersionUID = -6520786458950516097L; private boolean fromStart = false, toEnd = false; private K fromKey, toKey; private Object readResolve() { return new AscendingSubMap<>(TreeMap.this, fromStart, fromKey, true, toEnd, toKey, false); } public Set<Map.Entry<K,V>> entrySet() { throw new InternalError(); } public K lastKey() { throw new InternalError(); } public K firstKey() { throw new InternalError(); } public SortedMap<K,V> subMap(K fromKey, K toKey) { throw new InternalError(); } public SortedMap<K,V> headMap(K toKey) { throw new InternalError(); } public SortedMap<K,V> tailMap(K fromKey) { throw new InternalError(); } public Comparator<? super K> comparator() { throw new InternalError(); } } // 表示紅黑樹接電點的顏色 private static final boolean RED = false; private static final boolean BLACK = true; /** * 節點類,用來存儲TreeMap每一個節點的信息 */ static final class Entry<K,V> implements Map.Entry<K,V> { K key;//鍵 V value;//值 Entry<K,V> left;//左子節點 Entry<K,V> right;//右子節點 Entry<K,V> parent;//父節點 boolean color = BLACK;//節點顏色,默認爲黑色 /** * 構造方法 */ Entry(K key, V value, Entry<K,V> parent) { this.key = key; this.value = value; this.parent = parent; } /** * 返回key */ public K getKey() { return key; } /** * 返回value */ public V getValue() { return value; } /** * 設置value */ public V setValue(V value) { V oldValue = this.value; this.value = value; return oldValue; } /** * 判斷節點和對象是否相等 */ public boolean equals(Object o) { if (!(o instanceof Map.Entry)) return false; Map.Entry<?,?> e = (Map.Entry<?,?>)o; return valEquals(key,e.getKey()) && valEquals(value,e.getValue()); } /** * 返回節點的hashcode值,是節點的key和value的hashcode而後進行與運算 */ public int hashCode() { int keyHash = (key==null ? 0 : key.hashCode()); int valueHash = (value==null ? 0 : value.hashCode()); return keyHash ^ valueHash; } public String toString() { return key + "=" + value; } } /** * 獲取第一個節點,也是最小的節點 */ final Entry<K,V> getFirstEntry() { Entry<K,V> p = root; if (p != null) while (p.left != null) p = p.left; return p; } /** * 獲取最後一個節點,也是最大節點 */ final Entry<K,V> getLastEntry() { Entry<K,V> p = root; if (p != null) while (p.right != null) p = p.right; return p; } /** * 返回節點t的後繼節點,也就是大於t節點的最小節點 */ static <K,V> TreeMap.Entry<K,V> successor(Entry<K,V> t) { if (t == null) return null; else if (t.right != null) {//若是該節點有右子節點,就找右子節點的 左子節點,一直往下找 Entry<K,V> p = t.right; while (p.left != null) p = p.left; return p; } else {//若是該節點沒有右子節點,就向上找 Entry<K,V> p = t.parent; Entry<K,V> ch = t; while (p != null && ch == p.right) {//若是當前節點是父節點的右子節點,就一直往上找,直到找到一個節點是其父節點的左子節點,那個父節點就是要找的節點 ch = p; p = p.parent; } return p; } } /** * 返回小於t的最大節點。 */ static <K,V> Entry<K,V> predecessor(Entry<K,V> t) { if (t == null) return null; else if (t.left != null) {//若是該節點寸在左子節點,那麼要找的節點就是左子節點的右子節點(一直找到最後一個) Entry<K,V> p = t.left; while (p.right != null) p = p.right; return p; } else {//若是該節點沒有左子節點,就一直往上找,直到找到一個節點是其父節點的右子節點,那個父節點就是要找的節點 Entry<K,V> p = t.parent; Entry<K,V> ch = t; while (p != null && ch == p.left) { ch = p; p = p.parent; } return p; } } //返回節點的顏色 private static <K,V> boolean colorOf(Entry<K,V> p) { return (p == null ? BLACK : p.color); } //返回節點的父節點 private static <K,V> Entry<K,V> parentOf(Entry<K,V> p) { return (p == null ? null: p.parent); } //設置節點的顏色 private static <K,V> void setColor(Entry<K,V> p, boolean c) { if (p != null) p.color = c; } //返回節點的左子節點 private static <K,V> Entry<K,V> leftOf(Entry<K,V> p) { return (p == null) ? null: p.left; } //返回節點的右子節點 private static <K,V> Entry<K,V> rightOf(Entry<K,V> p) { return (p == null) ? null: p.right; } /** From CLR 左旋的過程是將p的右子樹繞p逆時針旋轉,使得p的右子樹成爲p的父親,同時修改相關節點的引用。旋轉以後,二叉查找樹的屬性仍然知足。*/ private void rotateLeft(Entry<K,V> p) { if (p != null) { Entry<K,V> r = p.right; p.right = r.left; if (r.left != null) r.left.parent = p; r.parent = p.parent; if (p.parent == null) root = r; else if (p.parent.left == p) p.parent.left = r; else p.parent.right = r; r.left = p; p.parent = r; } } /** From CLR 右旋的過程是將p的左子樹繞p順時針旋轉,使得p的左子樹成爲p的父親,同時修改相關節點的引用。旋轉以後,二叉查找樹的屬性仍然知足。 */ private void rotateRight(Entry<K,V> p) { if (p != null) { Entry<K,V> l = p.left; p.left = l.right; if (l.right != null) l.right.parent = p; l.parent = p.parent; if (p.parent == null) root = l; else if (p.parent.right == p) p.parent.right = l; else p.parent.left = l; l.right = p; p.parent = l; } } /** From CLR 在加入新的節點後,樹的平衡有可能被破壞,因此須要對TreeMap的樹結構進行修復*/ private void fixAfterInsertion(Entry<K,V> x) { x.color = RED;//先將當前接節點的顏色設置爲紅 while (x != null && x != root && x.parent.color == RED) {//若是父節點是黑色的,那麼無需進行任何操做。 if (parentOf(x) == leftOf(parentOf(parentOf(x)))) {//若是父節點是祖節點的左子節點 Entry<K,V> y = rightOf(parentOf(parentOf(x)));//祖節點的右子節點,就稱爲當前節點的叔節點 if (colorOf(y) == RED) {//若是叔節點的顏色爲red,則祖節點確定爲黑色。這樣直接將父節點和叔節點都設置爲黑色,祖節點設置爲紅色 setColor(parentOf(x), BLACK); setColor(y, BLACK); setColor(parentOf(parentOf(x)), RED); x = parentOf(parentOf(x));//以祖節點爲基準點繼續上述操做 } else {//若是叔節點爲黑色 if (x == rightOf(parentOf(x))) {//若是當前節點是父節點的右子節點,以父節點爲基準點,而後對父節點進行左旋。 x = parentOf(x); rotateLeft(x); } setColor(parentOf(x), BLACK);//將基準節點的父節點變黑,祖節點變紅,對祖節點進行右旋操做 setColor(parentOf(parentOf(x)), RED); rotateRight(parentOf(parentOf(x))); } } else {//若是父節點是祖節點的右子節點 Entry<K,V> y = leftOf(parentOf(parentOf(x))); if (colorOf(y) == RED) {//若是叔節點爲紅色,就將叔節點和父節點都設置爲黑色,祖節點設置爲紅色。再以祖節點做爲基準點繼續上述操做 setColor(parentOf(x), BLACK); setColor(y, BLACK); setColor(parentOf(parentOf(x)), RED); x = parentOf(parentOf(x)); } else {//若是叔節點是黑色 if (x == leftOf(parentOf(x))) {//若是當前節點是父節點的左子節點,就以父節點爲基準節點進行右旋操做。 x = parentOf(x); rotateRight(x); } setColor(parentOf(x), BLACK);//將基準點的父節點設置爲黑色,祖節點設置爲紅色。而後對基準點的祖節點進行左旋操做 setColor(parentOf(parentOf(x)), RED); rotateLeft(parentOf(parentOf(x))); } } } root.color = BLACK;//將根節點設置爲黑色 } /** * 刪除節點並從新平衡整棵樹,使它符合紅黑樹 */ private void deleteEntry(Entry<K,V> p) { modCount++; size--; //將p的後繼節點的key和value賦值給p而後將p指向p的後繼節點 if (p.left != null && p.right != null) { Entry<K,V> s = successor(p); p.key = s.key; p.value = s.value; p = s; } // p has 2 children // Start fixup at replacement node, if it exists. //開始修正替代節點,若是它存在 Entry<K,V> replacement = (p.left != null ? p.left : p.right); if (replacement != null) {//若是替代節點存在 // Link replacement to parent replacement.parent = p.parent; if (p.parent == null)//將p節點的父節點設置爲replacement的父節點,若是p節點的父節點不存在,則將replacement設置爲根節點 root = replacement; else if (p == p.parent.left)//若是p節點的父節點存在,就將replacement替換掉 p.parent.left = replacement; else p.parent.right = replacement; // Null out links so they are OK to use by fixAfterDeletion. //將p節點和其餘的節點之間斷開聯繫 p.left = p.right = p.parent = null; // Fix replacement if (p.color == BLACK)//若是p節點的顏色是黑色,就須要對樹結構進行調整 fixAfterDeletion(replacement); } else if (p.parent == null) { // return if we are the only node. root = null; } else { // No children. Use self as phantom replacement and unlink. if (p.color == BLACK) fixAfterDeletion(p); if (p.parent != null) { if (p == p.parent.left) p.parent.left = null; else if (p == p.parent.right) p.parent.right = null; p.parent = null; } } } /** From CLR 刪除節點後將樹修復爲紅黑樹結構*/ private void fixAfterDeletion(Entry<K,V> x) { while (x != root && colorOf(x) == BLACK) { if (x == leftOf(parentOf(x))) { Entry<K,V> sib = rightOf(parentOf(x)); if (colorOf(sib) == RED) { setColor(sib, BLACK); setColor(parentOf(x), RED); rotateLeft(parentOf(x)); sib = rightOf(parentOf(x)); } if (colorOf(leftOf(sib)) == BLACK && colorOf(rightOf(sib)) == BLACK) { setColor(sib, RED); x = parentOf(x); } else { if (colorOf(rightOf(sib)) == BLACK) { setColor(leftOf(sib), BLACK); setColor(sib, RED); rotateRight(sib); sib = rightOf(parentOf(x)); } setColor(sib, colorOf(parentOf(x))); setColor(parentOf(x), BLACK); setColor(rightOf(sib), BLACK); rotateLeft(parentOf(x)); x = root; } } else { // symmetric Entry<K,V> sib = leftOf(parentOf(x)); if (colorOf(sib) == RED) { setColor(sib, BLACK); setColor(parentOf(x), RED); rotateRight(parentOf(x)); sib = leftOf(parentOf(x)); } if (colorOf(rightOf(sib)) == BLACK && colorOf(leftOf(sib)) == BLACK) { setColor(sib, RED); x = parentOf(x); } else { if (colorOf(leftOf(sib)) == BLACK) { setColor(rightOf(sib), BLACK); setColor(sib, RED); rotateLeft(sib); sib = leftOf(parentOf(x)); } setColor(sib, colorOf(parentOf(x))); setColor(parentOf(x), BLACK); setColor(leftOf(sib), BLACK); rotateRight(parentOf(x)); x = root; } } } setColor(x, BLACK); } private static final long serialVersionUID = 919286545866124006L; /** * 從流中讀取對象 */ private void writeObject(java.io.ObjectOutputStream s) throws java.io.IOException { // Write out the Comparator and any hidden stuff s.defaultWriteObject(); // Write out size (number of Mappings) s.writeInt(size); // Write out keys and values (alternating) for (Iterator<Map.Entry<K,V>> i = entrySet().iterator(); i.hasNext(); ) { Map.Entry<K,V> e = i.next(); s.writeObject(e.getKey()); s.writeObject(e.getValue()); } } /** * 將對象寫入流中 */ private void readObject(final java.io.ObjectInputStream s) throws java.io.IOException, ClassNotFoundException { // Read in the Comparator and any hidden stuff s.defaultReadObject(); // Read in size int size = s.readInt(); buildFromSorted(size, null, s, null); } /** Intended to be called only from TreeSet.readObject */ void readTreeSet(int size, java.io.ObjectInputStream s, V defaultVal) throws java.io.IOException, ClassNotFoundException { buildFromSorted(size, null, s, defaultVal); } /** Intended to be called only from TreeSet.addAll */ void addAllForTreeSet(SortedSet<? extends K> set, V defaultVal) { try { buildFromSorted(set.size(), set.iterator(), null, defaultVal); } catch (java.io.IOException cannotHappen) { } catch (ClassNotFoundException cannotHappen) { } } /** * Linear time tree building algorithm from sorted data. Can accept keys * and/or values from iterator or stream. This leads to too many * parameters, but seems better than alternatives. The four formats * that this method accepts are: * * 1) An iterator of Map.Entries. (it != null, defaultVal == null). * 2) An iterator of keys. (it != null, defaultVal != null). * 3) A stream of alternating serialized keys and values. * (it == null, defaultVal == null). * 4) A stream of serialized keys. (it == null, defaultVal != null). * * It is assumed that the comparator of the TreeMap is already set prior * to calling this method. * * @param size the number of keys (or key-value pairs) to be read from * the iterator or stream * @param it If non-null, new entries are created from entries * or keys read from this iterator. * @param str If non-null, new entries are created from keys and * possibly values read from this stream in serialized form. * Exactly one of it and str should be non-null. * @param defaultVal if non-null, this default value is used for * each value in the map. If null, each value is read from * iterator or stream, as described above. * @throws java.io.IOException propagated from stream reads. This cannot * occur if str is null. * @throws ClassNotFoundException propagated from readObject. * This cannot occur if str is null. */ private void buildFromSorted(int size, Iterator<?> it, java.io.ObjectInputStream str, V defaultVal) throws java.io.IOException, ClassNotFoundException { this.size = size; root = buildFromSorted(0, 0, size-1, computeRedLevel(size), it, str, defaultVal); } /** * Recursive "helper method" that does the real work of the * previous method. Identically named parameters have * identical definitions. Additional parameters are documented below. * It is assumed that the comparator and size fields of the TreeMap are * already set prior to calling this method. (It ignores both fields.) * * @param level the current level of tree. Initial call should be 0. * @param lo the first element index of this subtree. Initial should be 0. * @param hi the last element index of this subtree. Initial should be * size-1. * @param redLevel the level at which nodes should be red. * Must be equal to computeRedLevel for tree of this size. */ @SuppressWarnings("unchecked") private final Entry<K,V> buildFromSorted(int level, int lo, int hi, int redLevel, Iterator<?> it, java.io.ObjectInputStream str, V defaultVal) throws java.io.IOException, ClassNotFoundException { /* * Strategy: The root is the middlemost element. To get to it, we * have to first recursively construct the entire left subtree, * so as to grab all of its elements. We can then proceed with right * subtree. * * The lo and hi arguments are the minimum and maximum * indices to pull out of the iterator or stream for current subtree. * They are not actually indexed, we just proceed sequentially, * ensuring that items are extracted in corresponding order. */ if (hi < lo) return null; int mid = (lo + hi) >>> 1; Entry<K,V> left = null; if (lo < mid) left = buildFromSorted(level+1, lo, mid - 1, redLevel, it, str, defaultVal); // extract key and/or value from iterator or stream K key; V value; if (it != null) { if (defaultVal==null) { Map.Entry<?,?> entry = (Map.Entry<?,?>)it.next(); key = (K)entry.getKey(); value = (V)entry.getValue(); } else { key = (K)it.next(); value = defaultVal; } } else { // use stream key = (K) str.readObject(); value = (defaultVal != null ? defaultVal : (V) str.readObject()); } Entry<K,V> middle = new Entry<>(key, value, null); // color nodes in non-full bottommost level red if (level == redLevel) middle.color = RED; if (left != null) { middle.left = left; left.parent = middle; } if (mid < hi) { Entry<K,V> right = buildFromSorted(level+1, mid+1, hi, redLevel, it, str, defaultVal); middle.right = right; right.parent = middle; } return middle; } /** * Find the level down to which to assign all nodes BLACK. This is the * last `full' level of the complete binary tree produced by * buildTree. The remaining nodes are colored RED. (This makes a `nice' * set of color assignments wrt future insertions.) This level number is * computed by finding the number of splits needed to reach the zeroeth * node. (The answer is ~lg(N), but in any case must be computed by same * quick O(lg(N)) loop.) */ private static int computeRedLevel(int sz) { int level = 0; for (int m = sz - 1; m >= 0; m = m / 2 - 1) level++; return level; } }
2、TreeMap的特色node
一、存入TreeMap的鍵值對的key是要能天然排序的(實現了Comparable接口),不然就要自定義一個比較器Comparator做爲參數傳入構造函數。緩存
二、TreeMap是以紅黑樹將數據組織在一塊兒,在添加或者刪除節點的時候有可能將紅黑樹的結構破壞了,因此須要判斷是否對紅黑樹進行修復。安全
三、因爲底層是紅黑樹結構,因此TreeMap的基本操做 containsKey、get、put 和 remove 的時間複雜度是 log(n) 。 併發
四、因爲TreeMap實現了NavigableMap,因此TreeMap有一系列的導航方法。app
3、比較器Comparator和實現Comparable接口ide
TreeMap中的鍵值對key要麼是可比較的,要麼就是TreeMap中有比較器,不然沒法加入TreeMap中。函數
一、建立比較器須要實現Comparator接口,而後實現其compare方法。使用比較器的時候只須要建立一個比較器實例而後傳入TreeMap的構造器工具
二、建立一個類實現Comparable接口,而後實現compareTo方法,是對象可比較oop
三、若是key自己具備天然比較性,同時TreeMap也有比較器那麼用比較器進行比較。
四、若是是經過key的自身排序則key不能爲null,若是是經過自定義比較器,那麼就看本身定義比較器的邏輯了。
//自定義比較器
public class MyComparator implements Comparator<MyEntity> { @Override public int compare(MyEntity e1, MyEntity e2) { int f = e1 == null ? (e2 == null ? 0 : -1) : (e2 == null ? 1 : 2); if(f == 2){ if(e1.getValue() > e2.getValue()){ return 1; }else if(e1.getValue() < e2.getValue()){ return -1; }else{ return 0; } } return f; } }
...
//讓對象可比較 public class MyEntity implements Comparable<MyEntity>{ private String name; private int value; public MyEntity(String name, int value) { super(); this.name = name; this.value = value; } public String getName() { return name; } public void setName(String name) { this.name = name; } public int getValue() { return value; } public void setValue(int value) { this.value = value; } @Override public String toString() { return "MyEntity [name=" + name + ", value=" + value + "]"; } @Override public int compareTo(MyEntity e) { if(value > e.getValue()){ return 1; }else if(value < e.getValue()){ return -1; }else{ return 0; } } }