一、类图

二、源码分析
a. 基于红黑树实现,使用 key 排序,Key 需要实现 Comparable 接口,或者创建时传入 Comparator
b. log(n) 时间复杂度
c. 原则上,Comparable / Comparator 处理相等应该与 equals 保持一致,否则就违背了 Map 的接口定义
但,TreeMap 查找 key 不再依赖 equals,而是直接基于 Comparable / Comparator,违背了也能正常工作
d. iterator 是 Fail-fast 的,遍历时被修改,会抛出 ConcurrentModificationException
f. 实现了序列化和克隆接口
g. putAll(Map m) 花费 n*log(n) 时间,使用 SortedMap 拷贝构造,花费线性时间
h. containsValue 花费线性时间(与 size 有关)
i. jdk 1.8 的集合都添加了并行(可分割)迭代器 Spliterator,采用了函数式编程框架,例如
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;
}// 只需要告诉你想如何处理集合元素(action),程序会自动并行化迭代
现在的三种 Set View 都支持两种 iterator,一种普通的 iterator ,另一种就是 spliterator
这些 spliterator 都是静态内部类实现的,各种 Set View 也是静态内部类,普通 Set View iterator 是内部类
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);
}
}
j. Entry 包含 key value left right parent color,红黑树节点
1万+

被折叠的 条评论
为什么被折叠?



