从源码理解TreeMap.java
package java.util;
import java.io.Serializable;
import java.util.function.BiConsumer;
import java.util.function.BiFunction;
import java.util.function.Consumer;
/**
* 基于红黑树的NavigableMap接口实现
* Map是根据关键字的自然比较序排序,或是根据创建时初始化的比较器的比较结果排序
* 这个实现保证提供log(n)时间的操作:containsKey、get、put、remove
* 树形Map的顺序是保持不变的,和其他有序Map一样,不管有没有提供显式的比较器,而且必须和equals兼容
* 注意,这个实现是不支持并发访问的。需要外部显式同步,如下:
* SortedMap m = Collections.synchronizedSortedMap(new TreeMap(...));
* 所有集合视图返回的迭代器都是快速失败的(fail-fast)
*/
public class TreeMap<K,V>
extends AbstractMap<K,V>
implements NavigableMap<K,V>, Cloneable, java.io.Serializable
{
/**
* 用于保持顺序的比较器,如果为空,使用自然序保持Key的顺序
*/
private final Comparator<? super K> comparator;
//根节点
private transient Entry<K,V> root = null;
/**
* 树中的结点数量
*/
private transient int size = 0;
/**
* 用于记录结构上的改变次数
*/
private transient int modCount = 0;
/**
* 构造方法一,默认构造方法,Comparator为空,即采用自然序维持TreeMap中结点的顺序
*/
public TreeMap() {
comparator = null;
}
/**
* 构造方法二,提供指定的比较器,如果为空,还是自然序
*/
public TreeMap(Comparator<? super K> comparator) {
this.comparator = comparator;
}
/**
* 构造方法三,采用自然序维持TreeMap中结点的顺序,同时将传入的Map中的内容添加到TreeMap中
*/
public TreeMap(Map<? extends K, ? extends V> m) {
comparator = null;
putAll(m);
}
/**
* 构造方法四,接受SortedMap参数,根据SortedMap的比较器维持TreeMap中的结点顺序,
* 同时通过buildFromSorted(int size, Iterator it,
* java.io.ObjectInputStream str, V defaultVal)方法将SortedMap中的 内容添加到TreeMap中
*/
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) {
}
}
// 查询操作
/**
* 返回Map中键值对数目
*/
public int size() {
return size;
}
/**
* 是否包含指定关键字
*/
public boolean containsKey(Object key) {
return getEntry(key) != null;
}
/**
* 是否包含指定值,时间复杂度和Map大小成正比
*/
public boolean containsValue(Object value) {
//通过e = successor(e)实现对树的遍历
for (Entry<K,V> e = getFirstEntry(); e != null; e = successor(e))
//判断结点值是否和value相等
if (valEquals(value, e.value))
return true;
//若没有,返回false
return false;
}
/**
* 返回指定关键字的值,没有则返回null
* 返回null不代表不存在,也有可能是值就是null
* @throws ClassCastException if the specified key cannot be compared
* with the keys currently in the map
* @throws NullPointerException if the specified key is null
* and this map uses natural ordering, or its comparator
* does not permit null keys
*/
public V get(Object key) {
Entry<K,V> p = getEntry(key);
return (p==null ? null : p.value);
}
public Comparator<? super K> comparator() {
return comparator;
}
/**
* @throws NoSuchElementException {@inheritDoc}
*/
public K firstKey() {
return key(getFirstEntry());
}
/**
* @throws NoSuchElementException {@inheritDoc}
*/
public K lastKey() {
return key(getLastEntry());
}
/**
* 将指定Map中的映射复制进来,会取代当前已存在的映射值
* @param map mappings to be stored in this map
* @throws ClassCastException if the class of a key or value in
* the specified map prevents it from being stored in this map
* @throws NullPointerException if the specified map is null or
* the specified map contains a null key and this map does not
* permit null keys
*/
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获取对应的结点
* @return this map's entry for the given key, or {@code null} if the map
* does not contain an entry for the key
* @throws ClassCastException if the specified key cannot be compared
* with the keys currently in the map
* @throws NullPointerException if the specified key is null
* and this map uses natural ordering, or its comparator
* does not permit null keys
*/
final Entry<K,V> getEntry(Object key) {
// 如果有比较器,返回getEntryUsingComparator(Object key)的结果
if (comparator != null)
return getEntryUsingComparator(key);
//查找的Key为null,抛出NullPointerException
if (key == null)
throw new NullPointerException();
@SuppressWarnings("unchecked")
//如果没有比较器,而是实现了 可比较接口
Comparable<? super K> k = (Comparable<? super K>) key;
//获取根节点
Entry<K,V> p = root;
//对树进行遍历查找结点
while (p != null) {
//把Key和当前节点的Key进行比较
int cmp = k.compareTo(p.key);
//Key小于当前结点的Key
if (cmp < 0)
//p“移动”到左节点上
p = p.left;
//key大于当前节点的Key
else if (cmp > 0)
//p移动到右结点上
p = p.right;
//key值相等则当前节点就是要找的结点
else
//返回找到的结点
return p;
}
//没有找到则返回null
return null;
}
/**
* 有比较器时获取指定关键字的Entry的方法
*/
final Entry<K,V> getEntryUsingComparator(Object key) {
@SuppressWarnings("unchecked")
K k = (K) key;
//获取比较器
Comparator<? super K> cpr = comparator;
//其实在调用此方法的get(Object key)中已经对比较器为null的情况进行判断,这里是防御性的判断
if (cpr != null) {
//获取根节点
Entry<K,V> p = root;
//遍历树
while (p != null) {
//获取Key和当前节点的Key的比较结果
int cmp = cpr.compare(k, p.key);
//查找的Key值较小
if (cmp < 0)
//p移动到左孩子
p = p.left;
//查找的Key值较大
else if (cmp > 0)
//p移动到右结点
p = p.right;
//key值相等
else
//返回找到的结点
return p;
}
}
//没找到Key值对应的结点,返回null
return null;
}
/**
* 获取指定关键字对应的Entry,如果没有就返回大于该关键字的最小关键字的Entry
* 如没有,返回null
*/
final Entry<K,V> getCeilingEntry(K key) {
Entry<K,V> p = root;
while (p != null) {
int cmp = compare(key, p.key);
//key比较小
if (cmp < 0) {
//进入左子树遍历
if (p.left != null)
p = p.left;
else
return p;
} else if (cmp > 0) { //key比较大
//进入右子树遍历
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
return p;
}
return null;
}
/**
* 获取指定关键字对应的Entry,如果没有对应的Entry,返回小于等于指定关键字的最大关键字的Entry,
* 如果不存在,返回null
*/
final Entry<K,V> getFloorEntry(K key) {
//获取根节点
Entry<K,V> p = root;
//不是空树,对树进行遍历
while (p != null) {
int cmp = compare(key, p.key);
//key较大
if (cmp > 0) {
//找到结点有右孩子,则继续向右孩子遍历
if (p.right != null)
p = p.right;
else //没有右孩子,那么p结点就是树中比传入key值小且最接近传入key的结点,就是要找的结点
return p;
} else if (cmp < 0) { //key值较小
//由左孩子向左孩子遍历
if (p.left != null) {
p = p.left;
} else { //没有左孩子,这个结点比key值大,
//返回内容是向上寻找到的根节点或比传入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 //Key值相等
return p;
}
return null;
}
/**
* 获取指定关键字对应的Entry,如果没有对应的Entry,返回严格大于指定关键字的最小关键字的Entry,
* 如果没有则返回null
*/
final Entry<K,V> getHigherEntry(K key) {
//获取根节点
Entry<K,V> p = root;
//树不空,遍历树
while (p != null) {
int cmp = compare(key, p.key);
//key比较小
if (cmp < 0) {
//有左孩子,去左子树遍历
if (p.left != null)
p = p.left;
else //没有左孩子,那么p结点就是树中比传入key值大且最接近传入key的结点了
return p;
} else { //key比较大
//有右子树,向右子树遍历
if (p.right != null) {
p = p.right;
} else { //没有右孩子,这个结点比key小,
//返回内容是向上寻找到根节点或是比传入key值大的最后一个结点
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;
}
/**
* 返回严格小于指定关键字的的最大关键字的Entry
*/
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;
}
/**将指定关键字和指定值联系起来,如已存在,覆盖
* @param key key with which the specified value is to be associated
* @param value value to be associated with the specified key
*
* @return the previous value associated with {@code key}, or
* {@code null} if there was no mapping for {@code key}.
* (A {@code null} return can also indicate that the map
* previously associated {@code null} with {@code key}.)
* @throws ClassCastException if the specified key cannot be compared
* with the keys currently in the map
* @throws NullPointerException if the specified key is null
* and this map uses natural ordering, or its comparator
* does not permit null keys
*/
public V put(K key, V value) {
Entry<K,V> t = root;
if (t == null) {
compare(key, key); // 类型检查(可能为null)
//如果根节点为null,将传入的键值对构造成根节点(根节点没有父节点,所以传入的父节点为null)
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) {
//do while实现从根节点root开始移动寻找传入键值对需要插入的位置
do {
//记录将要被插入新的键值对的上一个结点(即新节点的父节点)
parent = t;
//使用比较器比较父节点和插入键值对的Key值的大小
cmp = cpr.compare(key, t.key);
//插入的Key较大,进入左子树
if (cmp < 0)
t = t.left;
//插入的Key较小,进入右子树
else if (cmp > 0)
t = t.right;
//key值相等,替换并返回t结点的value(put方法结束)
else
return t.setValue(value);
} while (t != null);
}
//没有比较器的处理
else {
//Key为null,抛出NullPointerException异常
if (key == null)
throw new NullPointerException();
@SuppressWarnings("unchecked")
Comparable<? super K> k = (Comparable<? super K>) key;
//与if中的do while类似,只是比较的方式不同
do {
parent = t;
cmp = k.compareTo(t.key);
if (cmp < 0)
t = t.left;
else if (cmp > 0)
t = t.right;
else
return t.setValue(value);
} while (t != null);
}
//没有找到Key相同的结点才会有下面的操作
//根据传入的键值对和找到的“父节点”创建新节点
Entry<K,V> e = new Entry<>(key, value, parent);
//根据最后一次的判断结果确认新节点是“父节点”的左孩子还是右孩子
if (cmp < 0)
parent.left = e;
else
parent.right = e;
//对加入新节点的树进行调整
fixAfterInsertion(e);
//记录Size和modCount
size++;
modCount++;
//因为是插入新节点,所以返回是null
return null;
}
/**
* 删除指定关键字的映射
* @param key key for which mapping should be removed
* @return the previous value associated with {@code key}, or
* {@code null} if there was no mapping for {@code key}.
* (A {@code null} return can also indicate that the map
* previously associated {@code null} with {@code key}.)
* @throws ClassCastException if the specified key cannot be compared
* with the keys currently in the map
* @throws NullPointerException if the specified key is null
* and this map uses natural ordering, or its comparator
* does not permit null keys
*/
public V remove(Object key) {
//通过getEntry(Object key)获取结点
Entry<K,V> p = getEntry(key);
//指定Key的结点不存在,返回null
if (p == null)
return null;
//获取结点的value
V oldValue = p.value;
//删除结点
deleteEntry(p);
//返回结点的值
return oldValue;
}
/**
* 清空Map
*/
public void clear() {
modCount++;
size = 0;
root = null;
}
/**
* Returns a shallow copy of this {@code TreeMap} instance. (The keys and
* values themselves are not cloned.)
*
* @return a shallow copy of this map
*/
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接口的函数
/**
* @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;
}
/**
* @throws ClassCastException {@inheritDoc}
* @throws NullPointerException if the specified key is null
* and this map uses natural ordering, or its comparator
* does not permit null keys
* @since 1.6
*/
public Map.Entry<K,V> lowerEntry(K key) {
return exportEntry(getLowerEntry(key));
}
/**
* @throws ClassCastException {@inheritDoc}
* @throws NullPointerException if the specified key is null
* and this map uses natural ordering, or its comparator
* does not permit null keys
* @since 1.6
*/
public K lowerKey(K key) {
return keyOrNull(getLowerEntry(key));
}
/**
* @throws ClassCastException {@inheritDoc}
* @throws NullPointerException if the specified key is null
* and this map uses natural ordering, or its comparator
* does not permit null keys
* @since 1.6
*/
public Map.Entry<K,V> floorEntry(K key) {
return exportEntry(getFloorEntry(key));
}
/**
* @throws ClassCastException {@inheritDoc}
* @throws NullPointerException if the specified key is null
* and this map uses natural ordering, or its comparator
* does not permit null keys
* @since 1.6
*/
public K floorKey(K key) {
return keyOrNull(getFloorEntry(key));
}
/**
* @throws ClassCastException {@inheritDoc}
* @throws NullPointerException if the specified key is null
* and this map uses natural ordering, or its comparator
* does not permit null keys
* @since 1.6
*/
public Map.Entry<K,V> ceilingEntry(K key) {
return exportEntry(getCeilingEntry(key));
}
/**
* @throws ClassCastException {@inheritDoc}
* @throws NullPointerException if the specified key is null
* and this map uses natural ordering, or its comparator
* does not permit null keys
* @since 1.6
*/
public K ceilingKey(K key) {
return keyOrNull(getCeilingEntry(key));
}
/**
* @throws ClassCastException {@inheritDoc}
* @throws NullPointerException if the specified key is null
* and this map uses natural ordering, or its comparator
* does not permit null keys
* @since 1.6
*/
public Map.Entry<K,V> higherEntry(K key) {
return exportEntry(getHigherEntry(key));
}
/**
* @throws ClassCastException {@inheritDoc}
* @throws NullPointerException if the specified key is null
* and this map uses natural ordering, or its comparator
* does not permit null keys
* @since 1.6
*/
public K higherKey(K key) {
return keyOrNull(getHigherEntry(key));
}
// Views
/**
* Fields initialized to contain an instance of the entry set view
* the first time this view is requested. Views are stateless, so
* there's no reason to create more than one.
*/
private transient EntrySet entrySet = null;
private transient KeySet<K> navigableKeySet = null;
private transient NavigableMap<K,V> descendingMap = null;
/**
* Returns a {@link Set} view of the keys contained in this map.
*
* <p>The set's iterator returns the keys in ascending order.
* The set's spliterator is
* <em><a href="Spliterator.html#binding">late-binding</a></em>,
* <em>fail-fast</em>, and additionally reports {@link Spliterator#SORTED}
* and {@link Spliterator#ORDERED} with an encounter order that is ascending
* key order. The spliterator's comparator (see
* {@link java.util.Spliterator#getComparator()}) is {@code null} if
* the tree map's comparator (see {@link #comparator()}) is {@code null}.
* Otherwise, the spliterator's comparator is the same as or imposes the
* same total ordering as the tree map's comparator.
*
* <p>The set is backed by the map, so changes to the map are
* reflected in the set, and vice-versa. If the map is modified
* while an iteration over the set is in progress (except through
* the iterator's own {@code remove} operation), the results of
* the iteration are undefined. The set supports element removal,
* which removes the corresponding mapping from the map, via the
* {@code Iterator.remove}, {@code Set.remove},
* {@code removeAll}, {@code retainAll}, and {@code clear}
* operations. It does not support the {@code add} or {@code addAll}
* operations.
*/
public Set<K> keySet() {
return navigableKeySet();
}
public NavigableSet<K> navigableKeySet() {
KeySet<K> nks = navigableKeySet;
return (nks != null) ? nks : (navigableKeySet = new KeySet<>(this));
}
public NavigableSet<K> descendingKeySet() {
return descendingMap().navigableKeySet();
}
/**
* Returns a {@link Collection} view of the values contained in this map.
*
* <p>The collection's iterator returns the values in ascending order
* of the corresponding keys. The collection's spliterator is
* <em><a href="Spliterator.html#binding">late-binding</a></em>,
* <em>fail-fast</em>, and additionally reports {@link Spliterator#ORDERED}
* with an encounter order that is ascending order of the corresponding
* keys.
*
* <p>The collection is backed by the map, so changes to the map are
* reflected in the collection, and vice-versa. If the map is
* modified while an iteration over the collection is in progress
* (except through the iterator's own {@code remove} operation),
* the results of the iteration are undefined. The collection
* supports element removal, which removes the corresponding
* mapping from the map, via the {@code Iterator.remove},
* {@code Collection.remove}, {@code removeAll},
* {@code retainAll} and {@code clear} operations. It does not
* support the {@code add} or {@code addAll} operations.
*/
public Collection<V> values() {
Collection<V> vs = values;
return (vs != null) ? vs : (values = new Values());
}
/**
* Returns a {@link Set} view of the mappings contained in this map.
*
* <p>The set's iterator returns the entries in ascending key order. The
* sets's spliterator is
* <em><a href="Spliterator.html#binding">late-binding</a></em>,
* <em>fail-fast</em>, and additionally reports {@link Spliterator#SORTED} and
* {@link Spliterator#ORDERED} with an encounter order that is ascending key
* order.
*
* <p>The set is backed by the map, so changes to the map are
* reflected in the set, and vice-versa. If the map is modified
* while an iteration over the set is in progress (except through
* the iterator's own {@code remove} operation, or through the
* {@code setValue} operation on a map entry returned by the
* iterator) the results of the iteration are undefined. The set
* supports element removal, which removes the corresponding
* mapping from the map, via the {@code Iterator.remove},
* {@code Set.remove}, {@code removeAll}, {@code retainAll} and
* {@code clear} operations. It does not support the
* {@code add} or {@code addAll} operations.
*/
public Set<Map.Entry<K,V>> entrySet() {
EntrySet es = entrySet;
return (es != null) ? es : (entrySet = new EntrySet());
}
public NavigableMap<K, V> descendingMap() {
NavigableMap<K, V> km = descendingMap;
return (km != null) ? km :
(descendingMap = new DescendingSubMap<>(this,
true, null, true,
true, null, true));
}
/**
* @throws ClassCastException {@inheritDoc}
* @throws NullPointerException if {@code fromKey} or {@code toKey} is
* null and this map uses natural ordering, or its comparator
* does not permit null keys
* @throws IllegalArgumentException {@inheritDoc}
* @since 1.6
*/
public NavigableMap<K,V> subMap(K fromKey, boolean fromInclusive,
K toKey, boolean toInclusive) {
return new AscendingSubMap<>(this,
false, fromKey, fromInclusive,
false, toKey, toInclusive);
}
/**
* @throws ClassCastException {@inheritDoc}
* @throws NullPointerException if {@code toKey} is null
* and this map uses natural ordering, or its comparator
* does not permit null keys
* @throws IllegalArgumentException {@inheritDoc}
* @since 1.6
*/
public NavigableMap<K,V> headMap(K toKey, boolean inclusive) {
return new AscendingSubMap<>(this,
true, null, true,
false, toKey, inclusive);
}
/**
* @throws ClassCastException {@inheritDoc}
* @throws NullPointerException if {@code fromKey} is null
* and this map uses natural ordering, or its comparator
* does not permit null keys
* @throws IllegalArgumentException {@inheritDoc}
* @since 1.6
*/
public NavigableMap<K,V> tailMap(K fromKey, boolean inclusive) {
return new AscendingSubMap<>(this,
false, fromKey, inclusive,
true, null, true);
}
/**
* @throws ClassCastException {@inheritDoc}
* @throws NullPointerException if {@code fromKey} or {@code toKey} is
* null and this map uses natural ordering, or its comparator
* does not permit null keys
* @throws IllegalArgumentException {@inheritDoc}
*/
public SortedMap<K,V> subMap(K fromKey, K toKey) {
return subMap(fromKey, true, toKey, false);
}
/**
* @throws ClassCastException {@inheritDoc}
* @throws NullPointerException if {@code toKey} is null
* and this map uses natural ordering, or its comparator
* does not permit null keys
* @throws IllegalArgumentException {@inheritDoc}
*/
public SortedMap<K,V> headMap(K toKey) {
return headMap(toKey, false);
}
/**
* @throws ClassCastException {@inheritDoc}
* @throws NullPointerException if {@code fromKey} is null
* and this map uses natural ordering, or its comparator
* does not permit null keys
* @throws IllegalArgumentException {@inheritDoc}
*/
public SortedMap<K,V> tailMap(K fromKey) {
return tailMap(fromKey, true);
}
@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;
}
@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;
}
@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();
}
}
}
// 视图类支持
//集合类Values
class Values extends AbstractCollection<V> {
//提供集合类Values的迭代器
public Iterator<V> iterator() {
return new ValueIterator(getFirstEntry());
}
//返回TreeMap中保存的结点数
public int size() {
return TreeMap.this.size();
}
//判断TreeMap中是否存在Value为o的结点
public boolean contains(Object o) {
return TreeMap.this.containsValue(o);
}
//删除一个对象
public boolean remove(Object o) {
//遍历TreeMap
for (Entry<K,V> e = getFirstEntry(); e != null; e = successor(e)) {
//寻找值相等的结点
if (valEquals(e.getValue(), o)) {
//删除找到的结点
deleteEntry(e);
return true;
}
}
return false;
}
//清空TreeMap
public void clear() {
TreeMap.this.clear();
}
public Spliterator<V> spliterator() {
return new ValueSpliterator<K,V>(TreeMap.this, null, null, 0, -1, 0);
}
}
class EntrySet extends AbstractSet<Map.Entry<K,V>> {
//iterator()方法返回的是EntryIterator对象
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());
//判断是否包含某个对象的标准是存在结点的key与传入对象的key值相同,
//且该结点的value也与传入对象的value值相等
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());
//如果存在该对象,则进行删除操作并返回true
if (p != null && valEquals(p.getValue(), value)) {
deleteEntry(p);
return true;
}
//不存在直接返回false
return false;
}
//size()返回的是TreeMap中包含的结点的数量
public int size() {
return TreeMap.this.size();
}
//clear()方法实际调用了TreeMap的clear()方法,与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);
}
}
/*
* 与Values和EntrySet不同,KeySet类是静态的,
* KeySet实现了NavigableSet接口,意思是可导航的Set,包含更多的获取指定结点的方法
*/
Iterator<K> keyIterator() {
return new KeyIterator(getFirstEntry());
}
Iterator<K> descendingKeyIterator() {
return new DescendingKeyIterator(getLastEntry());
}
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();
}
//size()方法返回的是通过构造方法传入的Map的大小
public int size() { return m.size(); }
//判断传入的Map是否为空
public boolean isEmpty() { return m.isEmpty(); }
//判断传入的Map中是否包含这个Key
public boolean contains(Object o) { return m.containsKey(o); }
public void clear() { m.clear(); }
//因为传入的Map是NavigableMap,所以下面这几个方法都是代理方法,调用Map中相应的方法
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(); }
//获取传入Map的比较器
public Comparator<? super E> comparator() { return m.comparator(); }
//获取Map中第一个结点的key
public E pollFirst() {
Map.Entry<E,?> e = m.pollFirstEntry();
return (e == null) ? null : e.getKey();
}
//获取Map中最后一个结点的key
public E pollLast() {
Map.Entry<E,?> e = m.pollLastEntry();
return (e == null) ? null : e.getKey();
}
//删除一个对象,实际上是删除Map中以这个对象为key的一个结点
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);
}
}
/**
* TreeMap 迭代器相关的内部类
*/
abstract class PrivateEntryIterator<T> implements Iterator<T> {
//指向next的引用
Entry<K,V> next;
//保留对上一次返回结点的引用
Entry<K,V> lastReturned;
int expectedModCount;
//构造方法,lastReturned置空,next指向传入的结点
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移动它的后继
next = successor(e);
//记录被返回的结点
lastReturned = e;
//返回原先记录的next结点
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)
//如果被删除结点有两个孩子,删除结点e的时候e的引用会被修改为指向原结点的继承者,
//所以这里先保留next对lastReturned的引用,这样在删除结点后就能获取到继承者的引用,继而继续遍历树
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();
}
}
//value的迭代器
final class ValueIterator extends PrivateEntryIterator<V> {
ValueIterator(Entry<K,V> first) {
super(first);
}
//next()方法返回的是结点的value值
public V next() {
return nextEntry().value;
}
}
//key迭代器
final class KeyIterator extends PrivateEntryIterator<K> {
KeyIterator(Entry<K,V> first) {
super(first);
}
//next()方法返回的是结点的key
public K next() {
return nextEntry().key;
}
}
//逆序的key迭代器
final class DescendingKeyIterator extends PrivateEntryIterator<K> {
DescendingKeyIterator(Entry<K,V> first) {
super(first);
}
//next()方法返回的是结点的前一个结点(按遍历次序的前一个结点)的key
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;
}
}
// 工具函数
/**
* Compares two keys using the correct comparison method for this TreeMap.
*/
@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);
}
/**
* Test two values for equality. Differs from o1.equals(o2) only in
* that it copes with {@code null} o1 properly.
*/
static final boolean valEquals(Object o1, Object o2) {
return (o1==null ? o2==null : o1.equals(o2));
}
/**
* Return SimpleImmutableEntry for entry, or null if null
*/
static <K,V> Map.Entry<K,V> exportEntry(TreeMap.Entry<K,V> e) {
return (e == null) ? null :
new AbstractMap.SimpleImmutableEntry<>(e);
}
/**
* Return key for entry, or null if null
*/
static <K,V> K keyOrNull(TreeMap.Entry<K,V> e) {
return (e == null) ? null : e.key;
}
/**
* Returns the key corresponding to the specified Entry.
* @throws NoSuchElementException if the Entry is 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;
/**
* 存储内容的Map.
*/
final TreeMap<K,V> m;
/**
* 端点被表示为两个三元组(fromStart, lo,loInclusive)和(toEnd, hi, hiInclusive).
* 如果fromStart为真,下界lo无效,从Map中的第一个结点开始,如果loInclusive为真,下界包含lo
* 上界类似
*/
final K lo, hi; //lowKey、highKey
final boolean fromStart, toEnd; //标识Map的边界是否是Map的第一个结点和最后一个结点
final boolean loInclusive, hiInclusive; //是否包含最低lo、最高位置hi
//通过上面的三组变量可以组成两个三元组表示一个集合的两个端点
//构造方法
NavigableSubMap(TreeMap<K,V> m,
boolean fromStart, K lo, boolean loInclusive,
boolean toEnd, K hi, boolean hiInclusive) {
if (!fromStart && !toEnd) {
//lo>hi抛出异常
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;
}
// 内部工具函数
//tooLow判断传入的key是否太小
final boolean tooLow(Object key) {
//如果fromStart为false,需要判断最低边界
if (!fromStart) {
int c = m.compare(key, lo);
//如果key<lo或者(相等但是Map的边界不包含lo),那么key越界了,即小于最小值
if (c < 0 || (c == 0 && !loInclusive))
return true;
}
//默认返回false
return false;
}
//判断传入的key是否太大
final boolean tooHigh(Object key) {
if (!toEnd) {
int c = m.compare(key, hi);
if (c > 0 || (c == 0 && !hiInclusive))
return true;
}
return false;
}
//判断是否在范围内,即满足最低最高限制,结合tooLow和tooHigh即可
final boolean inRange(Object key) {
return !tooLow(key) && !tooHigh(key);
}
//是否在封闭的区间内
final boolean inClosedRange(Object key) {
return (fromStart || m.compare(key, lo) >= 0)
&& (toEnd || m.compare(hi, key) >= 0);
}
//判断是否在一个区间内
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() {
//如果fromStart为true,第一个结点就是最低结点,获取第一个结点
//否则根据loInclusive是否为true,即是否包含lo来决定获取Ceiling结点或Higher结点
//getCeilingEntry意为获取指定key的结点或者比指定key大的最小结点,不存在则返回null
//getHigherEntry意为获取比指定key大的最小结点,不存在则返回null
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;
}
//寻找大于等于key的最小结点
final TreeMap.Entry<K,V> absCeiling(K key) {
//如果key太小,返回绝对的最小的结点
if (tooLow(key))
return absLowest();
//获取允许的key的极限结点(满足要求的最小的结点)
TreeMap.Entry<K,V> e = m.getCeilingEntry(key);
return (e == null || tooHigh(e.key)) ? null : e;
}
//和absCeiling类似,只是获取的不包含相等的情况,而是寻找大于key的最小结点
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;
}
//获取绝对的小于等于key的结点
final TreeMap.Entry<K,V> absFloor(K key) {
//指定的key超出了hi,直接返回绝对的允许的最大的结点
if (tooHigh(key))
return absHighest();
//getFloorEntry获取的是指定key的结点,
//如果不存在这样的结点,就去获取比指定key小的最大结点,
//如果仍然不存在,返回null
TreeMap.Entry<K,V> e = m.getFloorEntry(key);
return (e == null || tooLow(e.key)) ? null : e;
}
//与absFloor类似,只是不包含等于的情况
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;
}
/** 返回比最大结点还要大的结点(Fence是栅栏、围栏的意思) */
final TreeMap.Entry<K,V> absHighFence() {
//如果toEnd是true,即上界是Map中的最大结点,那么围在它外面的是null,
//如果是false,根据hi是否被包含返回getHigherEntry或getCeilingEntry
return (toEnd ? null : (hiInclusive ?
m.getHigherEntry(hi) :
m.getCeilingEntry(hi)));
}
/** 为降序遍历返回比最小结点还要小的结点 */
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);
/** 返回升序迭代器from the perspective of this submap */
abstract Iterator<K> keyIterator();
abstract Spliterator<K> keySpliterator();
/** 返回降序迭代器from the perspective of this submap */
abstract Iterator<K> descendingKeyIterator();
// public methods
//如果fromStart、toEnd都是true,那么判断空、获取大小都是直接通过m,
//不然就必须使用entrySet()先获取结点集
public boolean isEmpty() {
return (fromStart && toEnd) ? m.isEmpty() : entrySet().isEmpty();
}
public int size() {
return (fromStart && toEnd) ? m.size() : entrySet().size();
}
//判断是否存在key先判断范围,再通过TreeMap的containsKey方法判断
public final boolean containsKey(Object key) {
return inRange(key) && m.containsKey(key);
}
//添加结点
public final V put(K key, V value) {
//判断要添加的key是否在范围内
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) {
//exportEntry(TreeMap.Entry<K,V> e)方法返回的是Map.Entry<K,V>对象
//它的key、value和传入结点的key、value相同
return exportEntry(subCeiling(key));
}
public final K ceilingKey(K key) {
//keyOrNull根据传入的结点是否是null返回null或返回结点的key(相当于提供了一个null安全的获取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;
}
// 视图
transient NavigableMap<K,V> descendingMapView = null;
transient EntrySetView entrySetView = null;
transient KeySet<K> navigableKeySetView = null;
//返回TreeMap的KeySet
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();
}
//逆序的KeySet
public NavigableSet<K> descendingKeySet() {
return descendingMap().navigableKeySet();
}
//返回一个子Map
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);
}
// 视图类
abstract class EntrySetView extends AbstractSet<Map.Entry<K,V>> {
private transient int size = -1, sizeModCount;
//返回子Map的大小
public int size() {
//如果fromStart和toEnd都是true,返回的是m的Size
if (fromStart && toEnd)
return m.size();
//size=-1或标记Size不同,重新计算一次size
if (size == -1 || sizeModCount != m.modCount) {
sizeModCount = m.modCount;
size = 0;
Iterator<?> i = iterator();
while (i.hasNext()) {
size++;
i.next();
}
}
return size;
}
//判断EntrySet是否为空
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();
//key不在范围内,返回false
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;
}
}
/**
* 子类SubMaps迭代器
*/
abstract class SubMapIterator<T> implements Iterator<T> {
TreeMap.Entry<K,V> lastReturned; //上一次被返回的结点
TreeMap.Entry<K,V> next; //下一个结点
final Object fenceKey; //栅栏key(如果是向大的方向遍历,不能访问key大于等于fenceKey的结点
//如果是向小的方向遍历,不能访问key小于等于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() {
//与普通的hasNext的判断不同,这里必须判断next的key是否超出了fenceKey
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;
}
//删除结点后可以继续遍历剩余的结点,因为删除前用next保留了lastReturned结点,
//而这个结点在删除操作的过程中被替换成了它的后继结点
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所指向的结点,这个结点的内容在删除lastReturned的时候被改变了
next = lastReturned;
m.deleteEntry(lastReturned);
lastReturned = null;
expectedModCount = m.modCount;
}
//删除之后next指向的结点其实被删除了,不能继续迭代访问
final void removeDescending() {
if (lastReturned == null)
throw new IllegalStateException();
if (m.modCount != expectedModCount)
throw new ConcurrentModificationException();
m.deleteEntry(lastReturned);
lastReturned = null;
expectedModCount = m.modCount;
}
}
//下面是几个内部类,都是对SubMapIterator的调用或间接调用
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();
}
}
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();
}
}
// Implement minimal Spliterator as KeySpliterator backup
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();
}
}
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;
}
}
}
/**
* AscendingSubMap继承自NavigableSubMap
*/
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();
}
//截取子Map
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);
}
//截取子Map,headMap通过构造方法就可以实现
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);
}
//tailMap
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());
}
//AscendingEntrySetView是一个视图类,重写了父类的iterator()方法,
//调用SubMapEntryIterator构造迭代器
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); }
}
/**
* DescendingSubMap也继承自NavigableSubMap
*/
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");
//因为DescendingSubMap表示的是逆序的Map,所以其实是通过获取原序的尾部实现的
return new DescendingSubMap<>(m,
false, toKey, inclusive,
toEnd, hi, hiInclusive);
}
//tailMap其实获取的是原序的头部
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); }
}
/**
* SubMap 继承自AbstractMap;这个类存在仅仅为了序列化兼容之前的版本不支持NavigableMap TreeMap。
* 它被翻译成一个旧版本AscendingSubMap子映射到一个新版本。这个类是从来没有以其他方式使用。
*/
private class SubMap extends AbstractMap<K,V>
implements SortedMap<K,V>, java.io.Serializable {
private static final long serialVersionUID = -6520786458950516097L;
//标识是否从Map的开始到结尾都属于子Map
private boolean fromStart = false, toEnd = false;
//开始位置和结束位置的key
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;
/**
* 树中结点的内部类Entry
*/
static final class Entry<K,V> implements Map.Entry<K,V> {
K key; //关键字Key
V value; //值value
Entry<K,V> left = null; //左孩子
Entry<K,V> right = null; //右孩子
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;
}
/**
* 判断结点相等的方法(两个结点为同一类型且Key值和value值都相等时两个结点相等)
*/
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());
}
/**
* 结点的哈希值计算方法
* @return
*/
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;
}
/**
* 返回指定结点的后继结点
*/
static <K,V> TreeMap.Entry<K,V> successor(Entry<K,V> t) {
//如果t本身是一个空结点,返回null
if (t == null)
return null;
//如果t有右孩子,找到右孩子的最左子孙结点
else if (t.right != null) {
Entry<K,V> p = t.right;
//获取p结点最左的子孙结点,如果存在的话
while (p.left != null)
p = p.left;
return p; //返回找到的后继结点
} else { //t不为null且没有右孩子
Entry<K,V> p = t.parent;
Entry<K,V> ch = t;
//沿着右孩子向上查找后继结点,直到根节点或找到结点ch是其父节点的左孩子的结点
while (p != null && ch == p.right) {
ch = p;
p = p.parent;
}
return p;
}
}
/**
* 返回指定结点的前一个结点
*/
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 {
//获取t的父节点
Entry<K,V> p = t.parent;
Entry<K,V> ch = t;
//沿着右孩子向上查找后继结点,直到根节点或找到结点ch是其父节点的右孩子的结点
while (p != null && ch == p.left) {
ch = p;
p = p.parent;
}
return p;
}
}
/**
* 平衡相关操作.
*
* Implementations of rebalancings during insertion and deletion are
* slightly different than the CLR version. Rather than using dummy
* nilnodes, we use a set of accessors that deal properly with null. They
* are used to avoid messiness surrounding nullness checks in the main
* algorithms.
*/
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;
}
/** 左旋 */
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;
}
}
/** 右旋 */
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;
}
}
//负责在插入结点后调整树结构和着色,以满足红黑树的要求
private void fixAfterInsertion(Entry<K,V> x) {
//插入结点默认为红色
x.color = RED;
//循环条件是x不为空、不是根节点、父节点的颜色是红色(如果父节点不是红色,则没有连续的红色结点,不再调整)
while (x != null && x != root && x.parent.color == RED) {
//x结点的父节点p是其父节点pp(p的父节点)的左孩子
if (parentOf(x) == leftOf(parentOf(parentOf(x)))) {
//获取pp结点的右孩子r
Entry<K,V> y = rightOf(parentOf(parentOf(x)));
//pp右孩子的颜色是红色(colorOf(Entry e)方法在e为空时返回black),不需要进行旋转操作
//(因为红黑树不是严格的平衡二叉树)
if (colorOf(y) == RED) {
//将x的父节点设置为黑色
setColor(parentOf(x), BLACK);
//y结点,即pp结点的右孩子r设置成黑色
setColor(y, BLACK);
//pp结点设置成红色
setColor(parentOf(parentOf(x)), RED);
//x移动到pp结点
x = parentOf(parentOf(x));
} else {
//父亲的兄弟是黑色的,这时需要进行旋转操作,根据是“内部”还是“外部”的情况决定是双旋转还是单旋转
//x结点是父节点的右孩子(因为上面已经确认p是pp的左孩子,所以这是一个“内部 ,左-右”插入的情况,需要进行双旋转处理)
if (x == rightOf(parentOf(x))) {
//x移动到它的父节点
x = parentOf(x);
//左旋操作
rotateLeft(x);
}
//x的父节点设置成黑色
setColor(parentOf(x), BLACK);
//x的父节点的父节点设置成红色
setColor(parentOf(parentOf(x)), RED);
//右旋操作
rotateRight(parentOf(parentOf(x)));
}
} else {
//获取x的父节点p的父节点pp的左孩子y
Entry<K,V> y = leftOf(parentOf(parentOf(x)));
//y结点是红色的
if (colorOf(y) == RED) {
//x的父节点,即p结点,设置成黑色
setColor(parentOf(x), BLACK);
//y结点设置成黑色
setColor(y, BLACK);
//pp结点设置成红色
setColor(parentOf(parentOf(x)), RED);
//x移动到pp结点
x = parentOf(parentOf(x));
} else {
//x是父节点的左孩子(因为上面已经确认p是pp的右孩子,所以这是一个“内部,右-左”插入的情况,需要进行双旋转处理)
if (x == leftOf(parentOf(x))) {
//x移动到父节点
x = parentOf(x);
//右旋操作
rotateRight(x);
}
//x的父节点设置成黑色
setColor(parentOf(x), BLACK);
//x的父节点的父节点设置成红色
setColor(parentOf(parentOf(x)), RED);
//左旋操作
rotateLeft(parentOf(parentOf(x)));
}
}
}
//根节点为黑色
root.color = BLACK;
}
/**
* 删除结点p,并重新平衡树
*/
private void deleteEntry(Entry<K,V> p) {
//记录树结构的修改次数
modCount++;
//记录树中结点的个数
size--;
//p有左右两个孩子的情况,标记为第一种
// 如果是严格意义上的内部情况,将p的后继复制到p中,然后让p指向后继结点
if (p.left != null && p.right != null) {
//获取后继结点(有两个孩子的情况下,后继结点肯定是右孩子或者右孩子的最左子孙)
Entry<K,V> s = successor(p);
//使用后继结点s替换要被删除的结点p,将后继结点的Key和value复制到p结点,之后将p指向后继结点
p.key = s.key;
p.value = s.value;
p = s;
} // p has 2 children
// Start fixup at replacement node, if it exists.
//开始修复被移除结点处的树结构
//如果p有左孩子,取左孩子,否则取右孩子,标记为第二种情况
Entry<K,V> replacement = (p.left != null ? p.left : p.right);
if (replacement != null) {
// Link replacement to parent
replacement.parent = p.parent;
//如果p结点没有父节点,即p结点是根节点
if (p.parent == null)
//将根节点替换为replacement结点
root = replacement;
//p是其父节点的左孩子
else if (p == p.parent.left)
//将p的父节点的left引用指向replacement
//这步操作实现了删除p的父节点到p结点的引用
p.parent.left = replacement;
else
//如果p是其父节点的右孩子,将父节点的right引用指向replacement
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)
//在删除结点后修复红黑树的颜色分配
fixAfterDeletion(replacement);
} else if (p.parent == null) { // return if we are the only node.
//进入这块代码说明p结点就是根节点
//如果标记第一种处p有左右孩子,则找到的后继结点s是p的一个祖先结点或右孩子或右孩子的最左子孙结点,
//他们要么有孩子结点,要么有父节点,所以如果进入这段代码,则说明标记第一种处的p结点没有左右两个孩子。
//没有左右孩子,则分没有孩子、有一个右孩子、有一个左孩子三种情况,只没有孩子的情况会使标记第一种的if判断不通过,
//所以p结点只能是没有孩子,加上这里的判断,p没有父节点,所以p是一个独立结点,也是树中的唯一结点
//所以将根节点设置为null即实现了对该结点的删除
root = null;
} else { // No children. Use self as phantom replacement and unlink.
if (p.color == BLACK)
//调整树结构
fixAfterDeletion(p);
//这个判断也一定会通过,因为p.parent如果是null,则在上面的else if块中已经被处理
if (p.parent != null) {
//p是一个左孩子
if (p == p.parent.left)
//删除父节点对p的引用
p.parent.left = null;
else if (p == p.parent.right) //p是一个右孩子
//删除父节点对p的引用
p.parent.right = null;
//删除p结点对父节点的引用
p.parent = null;
}
}
}
/**
* 删除之后的修复操作
*/
private void fixAfterDeletion(Entry<K,V> x) {
//循环处理,条件为x不是root结点且是黑色的(因为红色不会对红黑树的性质造成破坏,所以不需要调整)
while (x != root && colorOf(x) == BLACK) {
//x是一个左孩子
if (x == leftOf(parentOf(x))) {
//获取x的兄弟结点sib
Entry<K,V> sib = rightOf(parentOf(x));
//sib是红色的
if (colorOf(sib) == RED) {
//将sib设置成黑色
setColor(sib, BLACK);
//将父节点设置成红色
setColor(parentOf(x), RED);
//左旋父节点
rotateLeft(parentOf(x));
//sib移动到旋转后x的父节点p的右孩子
sib = rightOf(parentOf(x));
}
//sib的两个孩子的颜色都是黑色(null返回黑色)
if (colorOf(leftOf(sib)) == BLACK &&
colorOf(rightOf(sib)) == BLACK) {
//将sib设置成红色
setColor(sib, RED);
//x移动到x的父节点
x = parentOf(x);
} else { //sib的左右孩子都是黑色的不成立
//sib的右孩子是黑色的
if (colorOf(rightOf(sib)) == BLACK) {
//将sib的左孩子设置成黑色
setColor(leftOf(sib), BLACK);
//sib结点设置成红色
setColor(sib, RED);
//右旋操作
rotateRight(sib);
//sib移动到旋转后x父节点的右孩子
sib = rightOf(parentOf(x));
}
//sib设置成和x的父节点一样的颜色
setColor(sib, colorOf(parentOf(x)));
//x的父节点设置成黑色
setColor(parentOf(x), BLACK);
//sib的右孩子设置成黑色
setColor(rightOf(sib), BLACK);
//左旋操作
rotateLeft(parentOf(x));
//设置调整完的条件: x = root 跳出循环
x = root;
}
} else { // 对称情况,x是一个右孩子
//获取x的兄弟结点
Entry<K,V> sib = leftOf(parentOf(x));
//如果sib是红色的
if (colorOf(sib) == RED) {
//将sib设置为黑色
setColor(sib, BLACK);
//将x的父节点设置成红色
setColor(parentOf(x), RED);
//右旋
rotateRight(parentOf(x));
//sib移动到旋转后x父节点的左孩子
sib = leftOf(parentOf(x));
}
//sib的两个孩子的颜色都是黑色(null返回黑色)
if (colorOf(rightOf(sib)) == BLACK &&
colorOf(leftOf(sib)) == BLACK) {
//sib设置为红色
setColor(sib, RED);
//x移动到x的父节点
x = parentOf(x);
} else { //sib的两个孩子的颜色都是黑色(null返回黑色) 不成立
//sib的左孩子是黑色的,或者没有左孩子
if (colorOf(leftOf(sib)) == BLACK) {
//将sib的右孩子设置成黑色
setColor(rightOf(sib), BLACK);
//sib结点设置成红色
setColor(sib, RED);
//左旋
rotateLeft(sib);
//sib移动到x父节点的左孩子
sib = leftOf(parentOf(x));
}
//sib设置成和x的父节点一个颜色
setColor(sib, colorOf(parentOf(x)));
//x的父节点设置成黑色
setColor(parentOf(x), BLACK);
//sib的左孩子设置成黑色
setColor(leftOf(sib), BLACK);
//右旋
rotateRight(parentOf(x));
//设置跳出循环的标识
x = root;
}
}
}
//将x设置为黑色
setColor(x, BLACK);
}
private static final long serialVersionUID = 919286545866124006L;
/**
* Save the state of the {@code TreeMap} instance to a stream (i.e.,
* serialize it).
*
* @serialData The <em>size</em> of the TreeMap (the number of key-value
* mappings) is emitted (int), followed by the key (Object)
* and value (Object) for each key-value mapping represented
* by the TreeMap. The key-value mappings are emitted in
* key-order (as determined by the TreeMap's Comparator,
* or by the keys' natural ordering if the TreeMap has no
* Comparator).
*/
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());
}
}
/**
* Reconstitute the {@code TreeMap} instance from a stream (i.e.,
* deserialize it).
*/
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;
}
/**
* Currently, we support Spliterator-based versions only for the
* full map, in either plain of descending form, otherwise relying
* on defaults because size estimation for submaps would dominate
* costs. The type tests needed to check these for key views are
* not very nice but avoid disrupting existing class
* structures. Callers must use plain default spliterators if this
* returns null.
*/
static <K> Spliterator<K> keySpliteratorFor(NavigableMap<K,?> m) {
if (m instanceof TreeMap) {
@SuppressWarnings("unchecked") TreeMap<K,Object> t =
(TreeMap<K,Object>) m;
return t.keySpliterator();
}
if (m instanceof DescendingSubMap) {
@SuppressWarnings("unchecked") DescendingSubMap<K,?> dm =
(DescendingSubMap<K,?>) m;
TreeMap<K,?> tm = dm.m;
if (dm == tm.descendingMap) {
@SuppressWarnings("unchecked") TreeMap<K,Object> t =
(TreeMap<K,Object>) tm;
return t.descendingKeySpliterator();
}
}
@SuppressWarnings("unchecked") NavigableSubMap<K,?> sm =
(NavigableSubMap<K,?>) m;
return sm.keySpliterator();
}
final Spliterator<K> keySpliterator() {
return new KeySpliterator<K,V>(this, null, null, 0, -1, 0);
}
final Spliterator<K> descendingKeySpliterator() {
return new DescendingKeySpliterator<K,V>(this, null, null, 0, -2, 0);
}
/**
* Base class for spliterators. Iteration starts at a given
* origin and continues up to but not including a given fence (or
* null for end). At top-level, for ascending cases, the first
* split uses the root as left-fence/right-origin. From there,
* right-hand splits replace the current fence with its left
* child, also serving as origin for the split-off spliterator.
* Left-hands are symmetric. Descending versions place the origin
* at the end and invert ascending split rules. This base class
* is non-commital about directionality, or whether the top-level
* spliterator covers the whole tree. This means that the actual
* split mechanics are located in subclasses. Some of the subclass
* trySplit methods are identical (except for return types), but
* not nicely factorable.
*
* Currently, subclass versions exist only for the full map
* (including descending keys via its descendingMap). Others are
* possible but currently not worthwhile because submaps require
* O(n) computations to determine size, which substantially limits
* potential speed-ups of using custom Spliterators versus default
* mechanics.
*
* To boostrap initialization, external constructors use
* negative size estimates: -1 for ascend, -2 for descend.
*/
static class TreeMapSpliterator<K,V> {
final TreeMap<K,V> tree;
TreeMap.Entry<K,V> current; // traverser; initially first node in range
TreeMap.Entry<K,V> fence; // one past last, or null
int side; // 0: top, -1: is a left split, +1: right
int est; // size estimate (exact only for top-level)
int expectedModCount; // for CME checks
TreeMapSpliterator(TreeMap<K,V> tree,
TreeMap.Entry<K,V> origin, TreeMap.Entry<K,V> fence,
int side, int est, int expectedModCount) {
this.tree = tree;
this.current = origin;
this.fence = fence;
this.side = side;
this.est = est;
this.expectedModCount = expectedModCount;
}
final int getEstimate() { // force initialization
int s; TreeMap<K,V> t;
if ((s = est) < 0) {
if ((t = tree) != null) {
current = (s == -1) ? t.getFirstEntry() : t.getLastEntry();
s = est = t.size;
expectedModCount = t.modCount;
}
else
s = est = 0;
}
return s;
}
public final long estimateSize() {
return (long)getEstimate();
}
}
static final class KeySpliterator<K,V>
extends TreeMapSpliterator<K,V>
implements Spliterator<K> {
KeySpliterator(TreeMap<K,V> tree,
TreeMap.Entry<K,V> origin, TreeMap.Entry<K,V> fence,
int side, int est, int expectedModCount) {
super(tree, origin, fence, side, est, expectedModCount);
}
public KeySpliterator<K,V> trySplit() {
if (est < 0)
getEstimate(); // force initialization
int d = side;
TreeMap.Entry<K,V> e = current, f = fence,
s = ((e == null || e == f) ? null : // empty
(d == 0) ? tree.root : // was top
(d > 0) ? e.right : // was right
(d < 0 && f != null) ? f.left : // was left
null);
if (s != null && s != e && s != f &&
tree.compare(e.key, s.key) < 0) { // e not already past s
side = 1;
return new KeySpliterator<>
(tree, e, current = s, -1, est >>>= 1, expectedModCount);
}
return null;
}
public void forEachRemaining(Consumer<? super K> action) {
if (action == null)
throw new NullPointerException();
if (est < 0)
getEstimate(); // force initialization
TreeMap.Entry<K,V> f = fence, e, p, pl;
if ((e = current) != null && e != f) {
current = f; // exhaust
do {
action.accept(e.key);
if ((p = e.right) != null) {
while ((pl = p.left) != null)
p = pl;
}
else {
while ((p = e.parent) != null && e == p.right)
e = p;
}
} while ((e = p) != null && e != f);
if (tree.modCount != expectedModCount)
throw new ConcurrentModificationException();
}
}
public boolean tryAdvance(Consumer<? super K> action) {
TreeMap.Entry<K,V> e;
if (action == null)
throw new NullPointerException();
if (est < 0)
getEstimate(); // force initialization
if ((e = current) == null || e == fence)
return false;
current = successor(e);
action.accept(e.key);
if (tree.modCount != expectedModCount)
throw new ConcurrentModificationException();
return true;
}
public int characteristics() {
return (side == 0 ? Spliterator.SIZED : 0) |
Spliterator.DISTINCT | Spliterator.SORTED | Spliterator.ORDERED;
}
public final Comparator<? super K> getComparator() {
return tree.comparator;
}
}
static final class DescendingKeySpliterator<K,V>
extends TreeMapSpliterator<K,V>
implements Spliterator<K> {
DescendingKeySpliterator(TreeMap<K,V> tree,
TreeMap.Entry<K,V> origin, TreeMap.Entry<K,V> fence,
int side, int est, int expectedModCount) {
super(tree, origin, fence, side, est, expectedModCount);
}
public DescendingKeySpliterator<K,V> trySplit() {
if (est < 0)
getEstimate(); // force initialization
int d = side;
TreeMap.Entry<K,V> e = current, f = fence,
s = ((e == null || e == f) ? null : // empty
(d == 0) ? tree.root : // was top
(d < 0) ? e.left : // was left
(d > 0 && f != null) ? f.right : // was right
null);
if (s != null && s != e && s != f &&
tree.compare(e.key, s.key) > 0) { // e not already past s
side = 1;
return new DescendingKeySpliterator<>
(tree, e, current = s, -1, est >>>= 1, expectedModCount);
}
return null;
}
public void forEachRemaining(Consumer<? super K> action) {
if (action == null)
throw new NullPointerException();
if (est < 0)
getEstimate(); // force initialization
TreeMap.Entry<K,V> f = fence, e, p, pr;
if ((e = current) != null && e != f) {
current = f; // exhaust
do {
action.accept(e.key);
if ((p = e.left) != null) {
while ((pr = p.right) != null)
p = pr;
}
else {
while ((p = e.parent) != null && e == p.left)
e = p;
}
} while ((e = p) != null && e != f);
if (tree.modCount != expectedModCount)
throw new ConcurrentModificationException();
}
}
public boolean tryAdvance(Consumer<? super K> action) {
TreeMap.Entry<K,V> e;
if (action == null)
throw new NullPointerException();
if (est < 0)
getEstimate(); // force initialization
if ((e = current) == null || e == fence)
return false;
current = predecessor(e);
action.accept(e.key);
if (tree.modCount != expectedModCount)
throw new ConcurrentModificationException();
return true;
}
public int characteristics() {
return (side == 0 ? Spliterator.SIZED : 0) |
Spliterator.DISTINCT | Spliterator.ORDERED;
}
}
static final class ValueSpliterator<K,V>
extends TreeMapSpliterator<K,V>
implements Spliterator<V> {
ValueSpliterator(TreeMap<K,V> tree,
TreeMap.Entry<K,V> origin, TreeMap.Entry<K,V> fence,
int side, int est, int expectedModCount) {
super(tree, origin, fence, side, est, expectedModCount);
}
public ValueSpliterator<K,V> trySplit() {
if (est < 0)
getEstimate(); // force initialization
int d = side;
TreeMap.Entry<K,V> e = current, f = fence,
s = ((e == null || e == f) ? null : // empty
(d == 0) ? tree.root : // was top
(d > 0) ? e.right : // was right
(d < 0 && f != null) ? f.left : // was left
null);
if (s != null && s != e && s != f &&
tree.compare(e.key, s.key) < 0) { // e not already past s
side = 1;
return new ValueSpliterator<>
(tree, e, current = s, -1, est >>>= 1, expectedModCount);
}
return null;
}
public void forEachRemaining(Consumer<? super V> action) {
if (action == null)
throw new NullPointerException();
if (est < 0)
getEstimate(); // force initialization
TreeMap.Entry<K,V> f = fence, e, p, pl;
if ((e = current) != null && e != f) {
current = f; // exhaust
do {
action.accept(e.value);
if ((p = e.right) != null) {
while ((pl = p.left) != null)
p = pl;
}
else {
while ((p = e.parent) != null && e == p.right)
e = p;
}
} while ((e = p) != null && e != f);
if (tree.modCount != expectedModCount)
throw new ConcurrentModificationException();
}
}
public boolean tryAdvance(Consumer<? super V> action) {
TreeMap.Entry<K,V> e;
if (action == null)
throw new NullPointerException();
if (est < 0)
getEstimate(); // force initialization
if ((e = current) == null || e == fence)
return false;
current = successor(e);
action.accept(e.value);
if (tree.modCount != expectedModCount)
throw new ConcurrentModificationException();
return true;
}
public int characteristics() {
return (side == 0 ? Spliterator.SIZED : 0) | Spliterator.ORDERED;
}
}
static final class EntrySpliterator<K,V>
extends TreeMapSpliterator<K,V>
implements Spliterator<Map.Entry<K,V>> {
EntrySpliterator(TreeMap<K,V> tree,
TreeMap.Entry<K,V> origin, TreeMap.Entry<K,V> fence,
int side, int est, int expectedModCount) {
super(tree, origin, fence, side, est, expectedModCount);
}
public EntrySpliterator<K,V> trySplit() {
if (est < 0)
getEstimate(); // force initialization
int d = side;
TreeMap.Entry<K,V> e = current, f = fence,
s = ((e == null || e == f) ? null : // empty
(d == 0) ? tree.root : // was top
(d > 0) ? e.right : // was right
(d < 0 && f != null) ? f.left : // was left
null);
if (s != null && s != e && s != f &&
tree.compare(e.key, s.key) < 0) { // e not already past s
side = 1;
return new EntrySpliterator<>
(tree, e, current = s, -1, est >>>= 1, expectedModCount);
}
return null;
}
public void forEachRemaining(Consumer<? super Map.Entry<K, V>> action) {
if (action == null)
throw new NullPointerException();
if (est < 0)
getEstimate(); // force initialization
TreeMap.Entry<K,V> f = fence, e, p, pl;
if ((e = current) != null && e != f) {
current = f; // exhaust
do {
action.accept(e);
if ((p = e.right) != null) {
while ((pl = p.left) != null)
p = pl;
}
else {
while ((p = e.parent) != null && e == p.right)
e = p;
}
} while ((e = p) != null && e != f);
if (tree.modCount != expectedModCount)
throw new ConcurrentModificationException();
}
}
public boolean tryAdvance(Consumer<? super Map.Entry<K,V>> action) {
TreeMap.Entry<K,V> e;
if (action == null)
throw new NullPointerException();
if (est < 0)
getEstimate(); // force initialization
if ((e = current) == null || e == fence)
return false;
current = successor(e);
action.accept(e);
if (tree.modCount != expectedModCount)
throw new ConcurrentModificationException();
return true;
}
public int characteristics() {
return (side == 0 ? Spliterator.SIZED : 0) |
Spliterator.DISTINCT | Spliterator.SORTED | Spliterator.ORDERED;
}
@Override
public Comparator<Map.Entry<K, V>> getComparator() {
// Adapt or create a key-based comparator
if (tree.comparator != null) {
return Map.Entry.comparingByKey(tree.comparator);
}
else {
return (Comparator<Map.Entry<K, V>> & Serializable) (e1, e2) -> {
@SuppressWarnings("unchecked")
Comparable<? super K> k1 = (Comparable<? super K>) e1.getKey();
return k1.compareTo(e2.getKey());
};
}
}
}
}