Java数据结构之TreeMap
一、源码注释
/** * 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; } }
二、TreeMap的特点
1、存入TreeMap的键值对的key是要能自然排序的(实现了Comparable接口),否则就要自定义一个比较器Comparator作为参数传入构造函数。
2、TreeMap是以红黑树将数据组织在一起,在添加或者删除节点的时候有可能将红黑树的结构破坏了,所以需要判断是否对红黑树进行修复。
3、由于底层是红黑树结构,所以TreeMap的基本操作 containsKey、get、put 和 remove 的时间复杂度是 log(n) 。
4、由于TreeMap实现了NavigableMap,所以TreeMap有一系列的导航方法。
三、比较器Comparator和实现Comparable接口
TreeMap中的键值对key要么是可比较的,要么就是TreeMap中有比较器,否则无法加入TreeMap中。
1、创建比较器需要实现Comparator接口,然后实现其compare方法。使用比较器的时候只需要创建一个比较器实例然后传入TreeMap的构造器
2、创建一个类实现Comparable接口,然后实现compareTo方法,是对象可比较
3、如果key本身具有自然比较性,同时TreeMap也有比较器那么用比较器进行比较。
4、如果是通过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; } } }