TreeMap分析
第1部分 TreeMap介绍
TreeMap简介
TreeMap实现了Cloneable接口,要提供克隆方法。
TreeMap实现了Serializable接口,要提供序列化和反序列化方法。
TreeMap实现了“Navigable接口”,要提供范围、"临界"方法、比较器以及逆序迭代器,例如higher,ceiling,floor,lower等。
TreeMap构造函数
修饰语和返回类型 | 方法 | 描述 |
---|---|---|
public | TreeMap() | 默认构造函数 |
public | TreeMap(Comparator<? super K> comparator) | 传入比较器 |
public | TreeMap(Map<? extends K, ? extends V> m) | 传入映射m |
public | TreeMap(SortedMap<K, ? extends V> m) | 传入排序映射m |
TreeMap常用API
省略大部分"临界"key和entry的方法,以及获取集合,子映射的方法。
修饰语和返回类型 | 方法 | 描述 |
---|---|---|
int | size() | 元素个数 |
boolean | containsKey(Object key) | 包含key |
boolean | containsValue(Object value) | 包含value |
V | get(Object key) | 获取key对应的value |
Comparator<? super K> | comparator() | 获取比较器 |
K | firstKey() | 获取第一个(最"小")元素的key |
K | lastKey() | 获取最后一个(最"大")元素的key |
void | putAll(Map<? extends K, ? extends V> map) | 添加map中元素 |
V | put(K key, V value) | 插入元素 |
V | remove(Object key) | 移除key对应元素 |
void | clear() | 清空 |
Object | clone() | 克隆 |
Map.Entry<K,V> | firstEntry() | 获取第一个元素 |
Map.Entry<K,V> | lastEntry() | 获取最后一个元素 |
Map.Entry<K,V> | pollFirstEntry() | 移除第一个元素 |
Map.Entry<K,V> | firstEntry() | 获取第一个元素 |
第2部分 TreeMap数据结构
TreeMap的继承关系
java.lang.Object
↳ java.util.TreeMap<K, V>
↳
public class TreeMap<K,V> extends AbstractMap<K,V>
implements NavigableMap<K,V>, Cloneable, java.io.Serializable {}
TreeMap的关系图
图1 TreeMap的关系图
第3部分 TreeMap源码解析(基于JDK-8u201)
TreeMap与JDK8的HashMap相比,一个显著的区别是HashMap是每个桶中的链有可能转为红黑树,但是TreeMap没有桶的概念,整个数据结构就是一颗红黑树。
内部Entry结点
Entry结点是构成TreeMap的基本单位,因此在研究TreeMap之前先了解其内部结点是很有必要的。
//private static final boolean RED = false;
//private static final boolean BLACK = true;
static final class Entry<K,V> implements Map.Entry<K,V> {
K key;
V value;
Entry<K,V> left;
Entry<K,V> right;
Entry<K,V> parent;
boolean color = BLACK;//HashMap中标记红,而TreeMap标记黑
Entry(K key, V value, Entry<K,V> parent) {
this.key = key;
this.value = value;
this.parent = parent;
}
public K getKey() {
return key;
}
public V getValue() {
return 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;
//K,V相等就等价
return valEquals(key,e.getKey()) && valEquals(value,e.getValue());
}
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;
}
}
Entry的源码还是很简单的,只需要知道其标记黑色结点为true就行了。
TreeMap
在了解TreeMap源码前,如果对红黑树不了解的,可以看看这篇文章30张图带你彻底理解红黑树
public class TreeMap<K,V> extends AbstractMap<K,V>
implements NavigableMap<K,V>, Cloneable, java.io.Serializable
{
private final Comparator<? super K> comparator;//比较器
private transient Entry<K,V> root;
private transient int size = 0;
private transient int modCount = 0;
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);
}
public TreeMap(SortedMap<K, ? extends V> m) {
//SortedMap是有比较器成员的
comparator = m.comparator();
try {
//将元素添加进去,这个方法在后面
buildFromSorted(m.size(), m.entrySet().iterator(), null, null);
} catch (java.io.IOException cannotHappen) {
} catch (ClassNotFoundException cannotHappen) {
}
}
public int size() {
return size;
}
public boolean containsKey(Object key) {
return getEntry(key) != null;
}
public boolean containsValue(Object value) {
//遍历,获取下一个元素
for (Entry<K,V> e = getFirstEntry(); e != null; e = successor(e))
if (valEquals(value, e.value))
return true;
return false;
}
public V get(Object key) {
Entry<K,V> p = getEntry(key);
return (p==null ? null : p.value);
}
public Comparator<? super K> comparator() {
return comparator;
}
//first,last为"Sorted"的方法
public K firstKey() {
return key(getFirstEntry());
}
public K lastKey() {
return key(getLastEntry());
}
//添加map中元素
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;
}
}
//调用AbstractMap.putAll方法,该方法会调用TreeMap的put方法
super.putAll(map);
}
//根据key获取entry
final Entry<K,V> getEntry(Object key) {
//通过比较器获取
if (comparator != null)
return getEntryUsingComparator(key);
if (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;
}
//通过比较器查找
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的第一个元素
final Entry<K,V> getCeilingEntry(K key) {
Entry<K,V> p = root;
//对于红黑树中任意结点p,p的左边结点都小于p,右边相反
while (p != null) {
int cmp = compare(key, p.key);
if (cmp < 0) { //key比p小
if (p.left != null)//有左孩子继续找
p = p.left;
else
return p;
} else if (cmp > 0) {//key比p大
if (p.right != null) {
p = p.right;
} else {
/*左边的结点<p<key,因此,往父结点找
由于可能一直通过p = p.left和p = p.right找到叶子结点,因此,此时需要沿着路径回去,
找到第一个为其父亲左孩子的结点,这个父亲结点肯定是比key大,才会执行p = p.left操作,返回该父亲结点
*/
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;
}
//后面几个"临界"方法与上面类似,读者可自己推敲
//找到第一个小于等于key的元素
final Entry<K,V> getFloorEntry(K key) {
Entry<K,V> p = root;
while (p != null) {
int cmp = compare(key, p.key);
if (cmp > 0) {
if (p.right != null)
p = p.right;
else
return p;
} else if (cmp < 0) {
if (p.left != null) {
p = p.left;
} else {
Entry<K,V> parent = p.parent;
Entry<K,V> ch = p;
while (parent != null && ch == parent.left) {
ch = parent;
parent = parent.parent;
}
return parent;
}
} else
return p;
}
return null;
}
//找到第一个大于key的元素
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的元素
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;
}
//插入元素
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 {
parent = t;
cmp = cpr.compare(key, t.key);
if (cmp < 0)
t = t.left;
else if (cmp > 0)
t = t.right;
else //key相等,直接更新并返回,不用调整红黑树
return t.setValue(value);
} while (t != null);
}
else {
if (key == null)
throw new NullPointerException();
@SuppressWarnings("unchecked")
Comparable<? super K> k = (Comparable<? super K>) key;
do {
parent = t;
cmp = k.compareTo(t.key);
if (cmp < 0)
t = t.left;
else if (cmp > 0)
t = t.right;
else
return t.setValue(value);
} while (t != null);
}
Entry<K,V> e = new Entry<>(key, value, parent);
//根据上面的最后一次比较结果
if (cmp < 0)
parent.left = e;
else
parent.right = e;
//调整红黑树
fixAfterInsertion(e);
size++;
modCount++;
return null;
}
public V remove(Object key) {
Entry<K,V> p = getEntry(key);
if (p == null)
return null;
V oldValue = p.value;
deleteEntry(p);
return oldValue;
}
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;
}
public Map.Entry<K,V> firstEntry() {
return exportEntry(getFirstEntry());
}
public Map.Entry<K,V> lastEntry() {
return exportEntry(getLastEntry());
}
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;
}
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;
}
public Map.Entry<K,V> lowerEntry(K key) {
return exportEntry(getLowerEntry(key));
}
public K lowerKey(K key) {
return keyOrNull(getLowerEntry(key));
}
public Map.Entry<K,V> floorEntry(K key) {
return exportEntry(getFloorEntry(key));
}
public K floorKey(K key) {
return keyOrNull(getFloorEntry(key));
}
public Map.Entry<K,V> ceilingEntry(K key) {
return exportEntry(getCeilingEntry(key));
}
public K ceilingKey(K key) {
return keyOrNull(getCeilingEntry(key));
}
public Map.Entry<K,V> higherEntry(K key) {
return exportEntry(getHigherEntry(key));
}
public K higherKey(K key) {
return keyOrNull(getHigherEntry(key));
}
private transient EntrySet entrySet;
private transient KeySet<K> navigableKeySet;
private transient NavigableMap<K,V> descendingMap;
public Set<K> keySet() {
return navigableKeySet();
}
public NavigableSet<K> navigableKeySet() {
KeySet<K> nks = navigableKeySet;
//如果navigableKeySet还没创建对象,则创建
return (nks != null) ? nks : (navigableKeySet = new KeySet<>(this));
}
public NavigableSet<K> descendingKeySet() {
return descendingMap().navigableKeySet();
}
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());
}
//逆序集
public NavigableMap<K, V> descendingMap() {
NavigableMap<K, V> km = descendingMap;
return (km != null) ? km :
(descendingMap = new DescendingSubMap<>(this,
true, null, true,
true, null, true));
}
//fromInclusive,toInclusive表示左右边界是否包含
public NavigableMap<K,V> subMap(K fromKey, boolean fromInclusive,
K toKey, boolean toInclusive) {
return new AscendingSubMap<>(this,
false, fromKey, fromInclusive,
false, toKey, toInclusive);
}
public NavigableMap<K,V> headMap(K toKey, boolean inclusive) {
return new AscendingSubMap<>(this,
true, null, true,
false, toKey, inclusive);
}
public NavigableMap<K,V> tailMap(K fromKey, boolean inclusive) {
return new AscendingSubMap<>(this,
false, fromKey, inclusive,
true, null, true);
}
public SortedMap<K,V> subMap(K fromKey, K toKey) {
return subMap(fromKey, true, toKey, false);
}
public SortedMap<K,V> headMap(K toKey) {
return headMap(toKey, false);
}
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);
//k,v都能对应上才替换
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;
//遍历获取后一元素,successor(e)方法复杂度为O(logN)
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();
}
}
}
Iterator<K> keyIterator() {
return new KeyIterator(getFirstEntry());
}
//逆序迭代器,最后一个元素作为首元素
Iterator<K> descendingKeyIterator() {
return new DescendingKeyIterator(getLastEntry());
}
@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));
}
//转化类型,SimpleImmutableEntry只使用e的key,value
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;
}
static <K> K key(Entry<K,?> e) {
if (e==null)
throw new NoSuchElementException();
return e.key;
}
private static final Object UNBOUNDED = new Object();
// Red-black mechanics
private static final boolean RED = false;
private static final boolean BLACK = true;
//红黑树中最小的元素也就是最左结点
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) {
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;
}
}
//前一个结点,与上面类似
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);
}
//c表示是否为黑色
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;
}
/*左旋,其中p为支点
p r
/ \ / \
l r -----> p rr
/ \ / \
rl rr l rl
*/
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;
}
}
//插入x结点后调整红黑树
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) {
setColor(parentOf(x), BLACK);
setColor(y, BLACK);
setColor(parentOf(parentOf(x)), RED);
x = parentOf(parentOf(x));
} else {//父节点的兄弟结点为黑色
//若x为父节点右孩子,先左旋
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--;
//将下一元素作为替代元素
if (p.left != null && p.right != null) {
Entry<K,V> s = successor(p);
//将替代元素的内容拷贝过来
p.key = s.key;
p.value = s.value;
//p的索引指向替代元素
p = s;
}
//替代结点的子结点
Entry<K,V> replacement = (p.left != null ? p.left : p.right);
//将p的父子关系处理好
if (replacement != null) {
replacement.parent = p.parent;
if (p.parent == null)
root = replacement;
else if (p == p.parent.left)
p.parent.left = replacement;
else
p.parent.right = replacement;
//接触p的父子关系
p.left = p.right = p.parent = null;
// 删除后,调整红黑树
if (p.color == BLACK)
fixAfterDeletion(replacement);
} else if (p.parent == null) { //replacement==null,p.parent == null也就是只有p一个结点
root = null;
} else {//没有子结点
if (p.color == BLACK)
fixAfterDeletion(p);
//接触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;
}
}
}
//删除x后调整红黑树
private void fixAfterDeletion(Entry<K,V> x) {
while (x != root && colorOf(x) == BLACK) {
//x是父节点的左孩子
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));
}
//兄弟结点及其子结点都没有红色,设兄弟为红,像父b辈借
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 { //x是父节点的右孩子,与上面相反
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 {
s.defaultWriteObject();
s.writeInt(size);
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 {
s.defaultReadObject();
int size = s.readInt();
buildFromSorted(size, null, s, null);
}
void readTreeSet(int size, java.io.ObjectInputStream s, V defaultVal)
throws java.io.IOException, ClassNotFoundException {
buildFromSorted(size, null, s, defaultVal);
}
void addAllForTreeSet(SortedSet<? extends K> set, V defaultVal) {
try {
buildFromSorted(set.size(), set.iterator(), null, defaultVal);
} catch (java.io.IOException cannotHappen) {
} catch (ClassNotFoundException cannotHappen) {
}
}
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);
}
//通过中序遍历的方式构造红黑树
@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 {
if (hi < lo) return null;
int mid = (lo + hi) >>> 1;
Entry<K,V> left = null;
if (lo < mid)//构建左子树
left = buildFromSorted(level+1, lo, mid - 1, redLevel,
it, str, defaultVal);
//从迭代器或者流中获取元素
K key;
V value;
if (it != null) {//迭代器
if (defaultVal==null) {
Map.Entry<?,?> entry = (Map.Entry<?,?>)it.next();
key = (K)entry.getKey();
value = (V)entry.getValue();
} else {
key = (K)it.next();
value = defaultVal;
}
} else { //流
key = (K) str.readObject();
value = (defaultVal != null ? defaultVal : (V) str.readObject());
}
Entry<K,V> middle = new Entry<>(key, value, null);
// 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;
}
/*根结点为第0层,计算红色结点在那一层,把非满最底层设为红色,那么就能满足红黑树定义
根结点为黑色(如果只有一个结点,那么非满最底层为1,第0层还是黑色),不存在连续两个红结点,
根到叶子路径黑色结点相同
*/
private static int computeRedLevel(int sz) {
int level = 0;
for (int m = sz - 1; m >= 0; m = m / 2 - 1)
level++;
return level;
}
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);
}
}
以上源码中,最难的部分还是红黑树的调整上,结合注释应该还是能理解的。
三个集合
这三个集合中,前两个都只是简单的调用外部类方法,最后一个
ketset由于实现了NavigableSet,因此多了很多导航方法,但是也只是简单了调用了对应NavigableMap对象的方法。在源码中,使用该集合类的也只有TreeMap和NavigableSubMap,这两个类都实现了NavigableMap接口。
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);
}
}
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);
}
}
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);
}
}
迭代器
//PrivateEntryIterator是其他迭代器的抽象
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
/*由于删除lastReturned结点的时候,是将successors,也就是下个结点的k,v拷贝到lastReturned位置,并删除successor(替代结点)
因此,next指向lastReturned的索引,也就相当于删除后指向下个结点的索引
*/
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;//返回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();
/*由于逆序遍历,调用的是prevEntry()方法,也就是:
next = predecessor(e),将其指向前一个结点
然而deleteEntry方法不会改变前驱,因此next不需要改变,还是指向前驱
*/
deleteEntry(lastReturned);
lastReturned = null;
expectedModCount = modCount;
}
}
迭代器中,有理解难度的点都已经加上了注释,其他部分相信读者可以很容易看懂,因为有了之前阅读源码的积累,因此在后面看源码的过程中,需要理解的会越来越少,因为方法都类似。
子映射SubMap
//导航子映射,提供其他子映射的抽象
abstract static class NavigableSubMap<K,V> extends AbstractMap<K,V>
implements NavigableMap<K,V>, java.io.Serializable {
private static final long serialVersionUID = -2102997345730753016L;
final TreeMap<K,V> m;//所有元素
final K lo, hi;//(lo,hi)范围
final boolean fromStart, toEnd;//始末是否包括,用于headSubMap,tailSubMap
final boolean loInclusive, hiInclusive;//边界是否包括
NavigableSubMap(TreeMap<K,V> m,
boolean fromStart, K lo, boolean loInclusive,
boolean toEnd, K hi, boolean hiInclusive) {
//合法性检查
if (!fromStart && !toEnd) {
if (m.compare(lo, hi) > 0)
throw new IllegalArgumentException("fromKey > toKey");
} else {
if (!fromStart) // type check
m.compare(lo, lo);
if (!toEnd)
m.compare(hi, hi);
}
this.m = m;
this.fromStart = fromStart;
this.lo = lo;
this.loInclusive = loInclusive;
this.toEnd = toEnd;
this.hi = hi;
this.hiInclusive = hiInclusive;
}
final boolean tooLow(Object key) {
//fromStart==true代表无穷小
if (!fromStart) {
int c = m.compare(key, lo);//跟最小的比较
if (c < 0 || (c == 0 && !loInclusive))
return true;
}
return false;
}
final boolean tooHigh(Object key) {
if (!toEnd) {
int c = m.compare(key, hi);
if (c > 0 || (c == 0 && !hiInclusive))
return true;
}
return false;
}
//在范围内,边界由loInclusive和hiInclusive决定
final boolean inRange(Object key) {
return !tooLow(key) && !tooHigh(key);
}
//在闭区间[lo,hi]范围内
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);
}
//取最小的元素(个人觉得这个abs可以不加进去,容易让人想太多)
final TreeMap.Entry<K,V> absLowest() {
/*如果从最开始算起fromStart=true,第一个元素自然最小
如果最小的位置包括,那么大于等于lo的第一个,也就是lo自然最小
否则,大于lod的第一个自然最小
*/
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) {
if (tooLow(key))//太小了,取最小
return absLowest();
TreeMap.Entry<K,V> e = m.getCeilingEntry(key);
//拿到的值太大,越界了也要丢掉
return (e == null || tooHigh(e.key)) ? null : e;
}
//大于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) {
if (tooHigh(key))
return absHighest();
TreeMap.Entry<K,V> e = m.getFloorEntry(key);
return (e == null || tooLow(e.key)) ? null : e;
}
//小于key的第一个元素
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;
}
//比范围内都大
//(emmm顺便解释下这个单词,Fence:栅栏,圈住一块地的屏障,引申为范围)
final TreeMap.Entry<K,V> absHighFence() {
//toEnd 无穷大都在里面,那能是null了
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 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);
abstract Iterator<K> keyIterator();
abstract Spliterator<K> keySpliterator();
abstract Iterator<K> descendingKeyIterator();
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);
}
//NavigableSubMap内部类
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;
//key在范围内的情况下,比较值是否相等
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;
}
}
abstract class SubMapIterator<T> implements Iterator<T> {
TreeMap.Entry<K,V> lastReturned;
TreeMap.Entry<K,V> next;
final Object fenceKey;
int expectedModCount;
//first表示起始,fence表示末尾
SubMapIterator(TreeMap.Entry<K,V> first,
TreeMap.Entry<K,V> fence) {
expectedModCount = m.modCount;
lastReturned = null;
next = first;
//把null的转为UNBOUNDED
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);//获取下一个元素,TreeMap的方法
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;//需要修改next
m.deleteEntry(lastReturned);
lastReturned = null;
expectedModCount = m.modCount;
}
final void removeDescending() {
if (lastReturned == null)
throw new IllegalStateException();
if (m.modCount != expectedModCount)
throw new ConcurrentModificationException();
//不需修改next
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();
}
}
//逆序
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();
}
}
// key类型
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() {//调转方向,并取key类型
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;
}
}
}
//以上内容都为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();
}
//各种子映射,父类的abstract方法
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 {
//实现父类EntrySetView 没有实现的iterator()方法
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(); }
}
上面的代码比较多,但是内容并不是很复杂,NavigableSubMap是AscendingSubMap和DescendingSubMap的抽象类,两个子类分别是升序和逆序版本。而至于SubMap,在所有地方都找不到实现,官方的说法是,这个类只是为了序列化,与之前的版本兼容,并不是用来使用的。
旧版本使用的SubMap,但是已经用AscendingSubMap将其代替,因此不需要管这个类。
可分割迭代器
跟常规套路一样,先来个抽象类,然后对K,V,Entry类型进行实现,外加Navigable的一个逆序。其中参数side比较难理解,读者先不用管,后面会讲解。
static class TreeMapSpliterator<K,V> {
final TreeMap<K,V> tree;//所有元素
TreeMap.Entry<K,V> current; // 当前结点(下一个结点)
TreeMap.Entry<K,V> fence; // 最后一个结点
int side; // 0: top, -1: is a left split, +1: right
int est; // 预估容量,初始-1表示正序,-2表示逆序
int expectedModCount;
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) {
//初始-1表示正序,-2表示逆序
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);
}
//把side方向的子树切出来
public KeySpliterator<K,V> trySplit() {
if (est < 0)
getEstimate(); // 初始化
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);
//将[e.key,s.key)范围切出来
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());
};
}
}
}
上述源码中,只有side这个参数是比较难理解的,对于这种情况,静态代码看不懂的东西,就让它动起来,读者可以使用debug工具,但是那样也容易跟丢,最好的方法当然是自身能力够,也就是“肉眼debug”。
以KeySpliterator为例,这是个正序迭代器,另一个逆序的给读者练手。由于这个迭代过程不涉及颜色,因此就使用简单的二叉树结构。
从这个图可以看出元素间的大小关系,先大概了解下,对于后面理解有点帮助。
在类上按ctrl+shift+g查看谁调用了这个类,后面的调用就不详细讲,我会直接说明
final Spliterator<K> keySpliterator() {
return new KeySpliterator<K,V>(this, null, null, 0, -1, 0);
}
//int side; // 0: top, -1: is a left split, +1: right
其中倒数第三个参数也就是side=0,side上的含义为0表示最顶层,-1表示左部分,+1表示有部分,说明刚开始的时候为根结点
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);
}
接着执行了trySplit方法,其中我们关心的是这一部分
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);
此时d=side=0,因此s=root,什么意思呢?就是要把[e,root)切出来
而对于左部分来说,此时f=root,并将side设为-1,表示其为父亲的左部分
return new EntrySpliterator<>(tree, e, current = s, -1, est >>>= 1, expectedModCount);
而右子树current=s=root,正如我们上面的图看到那样,并令side = 1,表示其为父亲的有部分。
下面我们研究左部分,当其再次执行trySplit方法时,s=f.left=root.left,什么意思呢?如下
而root结点本来就不属于左子树的,其他部分请读者自行分析。
综上,就是把一棵树,按根结点切成两部分,将左子树创建新的可分割迭代器返回,其余部分保留,就相当于把一棵树从中间砍一半,并记录下其为原迭代器的左部分还是右部分。