private static final boolean RED = false; private static final boolean BLACK = true; 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; } ... ... }
private final Comparator<? super K> comparator; // 比較器 private transient Entry<K,V> root; // 紅黑樹根節點 private transient int size = 0; // 紅黑樹節點總數 private transient int modCount = 0; // // 調用put、remove、clear...方法時:modCount++(PrivateEntryIterator相關) public TreeMap() { // 天然排序(key實現Comparable) comparator = null; } public TreeMap(Comparator<? super K> comparator) { // 指定比較器 this.comparator = comparator; } public TreeMap(Map<? extends K, ? extends V> m) { // 用其它Map構建紅黑樹 comparator = null; putAll(m); } public TreeMap(SortedMap<K, ? extends V> m) { // 用其它有序Map構建紅黑樹 comparator = m.comparator(); try { buildFromSorted(m.size(), m.entrySet().iterator(), null, null); } catch (java.io.IOException cannotHappen) { } catch (ClassNotFoundException cannotHappen) { } }
public void putAll(Map<? extends K, ? extends V> map) { int mapSize = map.size(); if (size==0 && mapSize!=0 && map instanceof SortedMap) { // map爲有序Map 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); // 依次從map中取元素添加到當前紅黑樹中 } 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); } 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 { 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); 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 { // 從輸入流中獲取元素 key = (K) str.readObject(); value = (defaultVal != null ? defaultVal : (V) str.readObject()); } Entry<K,V> middle = new Entry<>(key, value, null); // 中置位節點 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; } private static int computeRedLevel(int sz) { // 樹中節點全滿的最後一層 int level = 0; for (int m = sz - 1; m >= 0; m = m / 2 - 1) level++; return level; }
在查找過程當中,採用比較器或天然順序比較節點大小:java
1‘ 指定比較器時,優先使用比較器比較節點大小app
2' 未指定比較器時,待查找鍵類型必須實現Comparable接口oop
public V get(Object key) { Entry<K,V> p = getEntry(key); return (p==null ? null : p.value); } final Entry<K,V> getEntry(Object key) { if (comparator != null) return getEntryUsingComparator(key); if (key == null) throw new NullPointerException(); 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; else if (cmp > 0) // 右拐 p = p.right; else // 找到節點 return p; } return null; } final Entry<K,V> getEntryUsingComparator(Object key) { 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; }
final int compare(Object k1, Object k2) { // 優先用comparator比較節點大小 return comparator==null ? ((Comparable<? super K>)k1).compareTo((K)k2) : comparator.compare((K)k1, (K)k2); } public Map.Entry<K,V> ceilingEntry(K key) { return exportEntry(getCeilingEntry(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) { if (p.left != null) // 左子樹存在則左拐 p = p.left; else // 左子樹不存在則當前節點爲ceiling return p; } else if (cmp > 0) { 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; } } else // key相等的節點爲ceiling return p; } return null; } public Map.Entry<K,V> floorEntry(K key) { return exportEntry(getFloorEntry(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) { if (p.right != null) // 右子樹存在則右拐 p = p.right; else // 右子樹不存在則當前節點爲floor return p; } else if (cmp < 0) { 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; } } else // key相等的節點爲floor return p; } return null; // 紅黑樹中不存在<=key的節點 }
static <K,V> Map.Entry<K,V> exportEntry(TreeMap.Entry<K,V> e) { return (e == null) ? null : new AbstractMap.SimpleImmutableEntry<>(e); }
containsKey:getEntry返回非空ui
containsValue:從第一個節點開始,遍歷整顆紅黑樹this
public boolean containsKey(Object key) { return getEntry(key) != null; } 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; } public Map.Entry<K,V> firstEntry() { // 最小節點 return exportEntry(getFirstEntry()); } final Entry<K,V> getFirstEntry() { Entry<K,V> p = root; if (p != null) while (p.left != null) // 一路左拐 p = p.left; return p; }
static <K,V> TreeMap.Entry<K,V> successor(Entry<K,V> t) { // 節點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; } }
1' 若已存在相同鍵的節點,則設置節點新值spa
2' 若不存在相同鍵的節點,則插入(黑色)節點,再以該節點爲支點進行平衡調整code
public V put(K key, V value) { Entry<K,V> t = root; if (t == null) { // 紅黑樹爲空 compare(key, key); // 可能comparator爲空,且key所屬類也未實現Comparable接口 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) { // comparator不爲空 do { parent = t; cmp = cpr.compare(key, t.key); if (cmp < 0) // 左拐 t = t.left; else if (cmp > 0) // 右拐 t = t.right; else // 存在key相等的節點 return t.setValue(value); } while (t != null); } else { // comparator爲空 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 // 存在key相等的節點 return t.setValue(value); } 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; } private void fixAfterInsertion(Entry<K,V> x) { x.color = RED; // x不爲空 && x不爲根節點 && x父節點爲紅色 while (x != null && x != root && x.parent.color == RED) { // 當前節點x if (parentOf(x) == leftOf(parentOf(parentOf(x)))) { // x父節點是x爺爺節點的左孩子 Entry<K,V> y = rightOf(parentOf(parentOf(x))); // x叔叔節點(可能不存在) if (colorOf(y) == RED) { // x叔叔節點爲紅色 setColor(parentOf(x), BLACK); setColor(y, BLACK); setColor(parentOf(parentOf(x)), RED); x = parentOf(parentOf(x)); // x爺爺節點做爲當前節點:continue } else { // x叔叔節點爲黑色 if (x == rightOf(parentOf(x))) { // x是父節點的右孩子 x = parentOf(x); rotateLeft(x); } // 此時,x是父節點的左孩子 setColor(parentOf(x), BLACK); setColor(parentOf(parentOf(x)), RED); rotateRight(parentOf(parentOf(x))); } } else { // x父節點是x爺爺節點的右孩子 || x爺爺節點不存在 Entry<K,V> y = leftOf(parentOf(parentOf(x))); // x叔叔節點(可能不存在) if (colorOf(y) == RED) { // x叔叔節點爲紅色 setColor(parentOf(x), BLACK); setColor(y, BLACK); setColor(parentOf(parentOf(x)), RED); x = parentOf(parentOf(x)); // x爺爺節點做爲當前節點:continue } else { // x叔叔節點爲黑色 if (x == leftOf(parentOf(x))) { // x是父節點的左孩子 x = parentOf(x); rotateRight(x); } // 此時,x是父節點的右孩子 setColor(parentOf(x), BLACK); setColor(parentOf(parentOf(x)), RED); rotateLeft(parentOf(parentOf(x))); } } } root.color = BLACK; // 根節點置爲黑色 } private static <K,V> boolean colorOf(Entry<K,V> p) { // 不存在的節點(如葉子節點)爲黑色 return (p == null ? BLACK : p.color); } private static <K,V> void setColor(Entry<K,V> p, boolean c) { // p不存在:noop if (p != null) p.color = c; } private static <K,V> Entry<K,V> parentOf(Entry<K,V> p) { // p不存在則p父節點也不存在 return (p == null ? null: p.parent); } private static <K,V> Entry<K,V> leftOf(Entry<K,V> p) { // p不存在則p左孩子也不存在 return (p == null) ? null: p.left; } private static <K,V> Entry<K,V> rightOf(Entry<K,V> p) { // p不存在則p右孩子也不存在 return (p == null) ? null: p.right; } private void rotateLeft(Entry<K,V> p) { // 以p爲支點左旋 if (p != null) { Entry<K,V> r = p.right; // p右孩子(必須存在) // 1. r左孩子 -> p右孩子 p.right = r.left; if (r.left != null) r.left.parent = p; r.parent = p.parent; if (p.parent == null) root = r; // 2. r -> 根節點 else if (p.parent.left == p) p.parent.left = r; // 2. r -> p父節點的左孩子 else p.parent.right = r; // 2. r -> p父節點的右孩子 // 3. p -> r的左孩子 r.left = p; p.parent = r; } } private void rotateRight(Entry<K,V> p) { // 以p爲支點右旋 if (p != null) { Entry<K,V> l = p.left; // p左孩子(必須存在) // 1. l右孩子 -> p左孩子 p.left = l.right; if (l.right != null) l.right.parent = p; l.parent = p.parent; if (p.parent == null) root = l; // 2. l -> 根節點 else if (p.parent.right == p) p.parent.right = l; // 2. l -> p父節點的右孩子 else p.parent.left = l; // 2. l -> p父節點的左孩子 // 3. p -> r的右孩子 l.right = p; p.parent = l; } }
1' 若未找到待刪除節點,則直接返回blog
2' 若待刪除節點左右子樹非空,則將successor的鍵值保存到待刪除節點,待刪除節點 = successor排序
3' 若待刪除節點左右子樹皆空繼承
1'' 待刪除節點爲黑色,以該節點爲支點進行平衡調整,再刪除該節點
2’‘ 待刪除節點爲紅色,直接刪除該節點
4' 若待刪除節點左右子樹非皆空
1'' 待刪除節點爲黑色,則刪除該節點,再以該節點左(右)孩子爲支點進行平衡調整
2'' 待刪除節點爲紅色,直接刪除該節點
public V remove(Object key) { Entry<K,V> p = getEntry(key); // 尋找節點 if (p == null) return null; V oldValue = p.value; deleteEntry(p); return oldValue; } private void deleteEntry(Entry<K,V> p) { modCount++; size--; if (p.left != null && p.right != null) { // p左右子樹非空 Entry<K,V> s = successor(p); p.key = s.key; p.value = s.value; p = s; } Entry<K,V> replacement = (p.left != null ? p.left : p.right); // p的左(右)孩子 if (replacement != null) { // p存在左(右)孩子,刪除p後進行平衡調整 replacement.parent = p.parent; if (p.parent == null) root = replacement; else if (p == p.parent.left) p.parent.left = replacement; else p.parent.right = replacement; p.left = p.right = p.parent = null; if (p.color == BLACK) fixAfterDeletion(replacement); } else if (p.parent == null) { // p爲紅黑樹惟一節點 root = null; } else { // p沒有孩子節點,平衡調整完後再刪除p 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; } } } private void fixAfterDeletion(Entry<K,V> x) { // x不爲根節點 && x爲黑色 while (x != root && colorOf(x) == BLACK) { // 當前節點x if (x == leftOf(parentOf(x))) { // x是x父節點的左孩子 Entry<K,V> sib = rightOf(parentOf(x)); // x兄弟節點(可能不存在) if (colorOf(sib) == RED) { // x兄弟節點爲紅色 setColor(sib, BLACK); setColor(parentOf(x), RED); rotateLeft(parentOf(x)); sib = rightOf(parentOf(x)); } // 此時,x兄弟節點爲黑色 // x兄弟節點:左孩子黑色,右孩子黑色 if (colorOf(leftOf(sib)) == BLACK && colorOf(rightOf(sib)) == BLACK) { setColor(sib, RED); x = parentOf(x); // x父節點做爲當前節點:continue } else { // x兄弟節點:左孩子紅色,右孩子黑色 if (colorOf(rightOf(sib)) == BLACK) { setColor(leftOf(sib), BLACK); setColor(sib, RED); rotateRight(sib); sib = rightOf(parentOf(x)); } // 此時,x兄弟節點爲黑色,x兄弟節點的右孩子爲紅色 setColor(sib, colorOf(parentOf(x))); setColor(parentOf(x), BLACK); setColor(rightOf(sib), BLACK); rotateLeft(parentOf(x)); x = root; } } else { // x是x父節點的右孩子 Entry<K,V> sib = leftOf(parentOf(x)); // x兄弟節點(可能不存在) if (colorOf(sib) == RED) { // x兄弟節點爲紅色 setColor(sib, BLACK); setColor(parentOf(x), RED); rotateRight(parentOf(x)); sib = leftOf(parentOf(x)); } // 此時,x兄弟節點爲黑色 // x兄弟節點:左孩子黑色,右孩子黑色 if (colorOf(rightOf(sib)) == BLACK && colorOf(leftOf(sib)) == BLACK) { setColor(sib, RED); x = parentOf(x); // x父節點做爲當前節點:continue } else { // x兄弟節點:左孩子黑色,右孩子紅色 if (colorOf(leftOf(sib)) == BLACK) { setColor(rightOf(sib), BLACK); setColor(sib, RED); rotateLeft(sib); sib = leftOf(parentOf(x)); } // 此時,x兄弟節點爲黑色,x兄弟節點的左孩子爲紅色 setColor(sib, colorOf(parentOf(x))); setColor(parentOf(x), BLACK); setColor(leftOf(sib), BLACK); rotateRight(parentOf(x)); x = root; } } } setColor(x, BLACK); }
依次返回EntrySet、KeySet、Values
1' EntrySet、KeySet繼承自AbstractSet,而Values繼承自AbstractCollection
2' EntrySet、KeySet、Values對應的迭代器分別爲:EntryIterator、KeyIterator、ValueIterator
3' EntryIterator、KeyIterator、ValueIterator均繼承自PrivateEntryIterator,依賴PrivateEntryIterator.nextEntry分別對Entry、K、V進行迭代
4' 對EntrySet、KeySet、Values,及各自迭代器,調用remove方法,都將最終調用TreeMap的deleteEntry方法刪除節點
5' 對EntrySet、KeySet、Values,不能調用add方法添加元素,不然將拋出UnsupportedOperationException
private transient EntrySet entrySet; private transient KeySet<K> navigableKeySet; public Set<Map.Entry<K,V>> entrySet() { EntrySet es = entrySet; return (es != null) ? es : (entrySet = new EntrySet()); } public Set<K> keySet() { return navigableKeySet(); } public NavigableSet<K> navigableKeySet() { KeySet<K> nks = navigableKeySet; return (nks != null) ? nks : (navigableKeySet = new KeySet<>(this)); } Iterator<K> keyIterator() { return new KeyIterator(getFirstEntry()); } public Collection<V> values() { Collection<V> vs = values; return (vs != null) ? vs : (values = new Values()); } class EntrySet extends AbstractSet<Map.Entry<K,V>> { public Iterator<Map.Entry<K,V>> iterator() { return new EntryIterator(getFirstEntry()); } public boolean contains(Object o); // TreeMap.this.getEntry public boolean remove(Object o); // TreeMap.this.deleteEntry // add方法繼承自AbstractCollection:throw UnsupportedOperationException ... ... } 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 boolean contains(Object o); // TreeMap.this.containsKey public boolean remove(Object o); // TreeMap.this.remove // add方法繼承自AbstractCollection:throw UnsupportedOperationException } class Values extends AbstractCollection<V> { public Iterator<V> iterator() { return new ValueIterator(getFirstEntry()); } public boolean contains(Object o); // TreeMap.this.containsValue public boolean remove(Object o); // TreeMap.this.deleteEntry // add方法繼承自AbstractCollection:throw UnsupportedOperationException ... ... }
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(); // next != null final Entry<K,V> nextEntry(); // TreeMap.this.successor final Entry<K,V> prevEntry(); // TreeMap.this.predecessor public void remove(); // TreeMap.this.deleteEntry } 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; } }
1’ tailMap是一個設置低位鍵(包括低位邊界),而未設置高位鍵的NavigableSubMap
2' 在>=低位鍵的範圍內,能夠對tailMap進行get、put、remove等操做
public SortedMap<K,V> tailMap(K fromKey) { return tailMap(fromKey, true); } public NavigableMap<K,V> tailMap(K fromKey, boolean inclusive) { return new AscendingSubMap<>(this, false, fromKey, inclusive, // 設置低位鍵 true, null, true); // 未設置高位鍵 } static final class AscendingSubMap<K,V> extends NavigableSubMap<K,V> { 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); } ... ... } abstract static class NavigableSubMap<K,V> extends AbstractMap<K,V> implements NavigableMap<K,V>, java.io.Serializable { final TreeMap<K,V> m; 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; } final boolean tooLow(Object key) { if (!fromStart) { // 設置了低位鍵 int c = m.compare(key, lo); if (c < 0 || (c == 0 && !loInclusive)) return true; } return false; } final boolean tooHigh(Object key) { if (!toEnd) { // 設置了高位鍵 int c = m.compare(key, hi); if (c > 0 || (c == 0 && !hiInclusive)) return true; } return false; } final boolean inRange(Object key) { return !tooLow(key) && !tooHigh(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); } ... ... }