疑问:TreeMap的clear()方法与LinkedList,ArrayList,HashMapd等的比较
一、定义
public class TreeMap<K,V>
extends AbstractMap<K,V>
implements NavigableMap<K,V>, Cloneable, java.io.Serializable
TreeMap扩展自AbstractMap
实现NavigableMap
实现Cloneable,实现Serializable
来看下NavigableMap
public interface SortedMap<K,V> extends Map<K,V> {
Comparator<? super K> comparator();
//返回formKey到toKey(不包括)间的视图
SortedMap<K,V> subMap(K fromKey, K toKey);
//返回小于toKey的视图
SortedMap<K,V> headMap(K toKey);
//返回小于tailMap的视图
SortedMap<K,V> tailMap(K fromKey);
//返回first key
K firstKey();
//返回last key
K lastKey();
//返回key视图,与SortMap存在映射关系,修改set<K>或SortedMap中的一个,另一个也会改变
Set<K> keySet();
Collection<V> values();
Set<Map.Entry<K, V>> entrySet();
}
public interface NavigableMap<K,V> extends SortedMap<K,V> {
Map.Entry<K,V> lowerEntry(K key);
K lowerKey(K key);
Map.Entry<K,V> floorEntry(K key);
K floorKey(K key);
Map.Entry<K,V> ceilingEntry(K key);
K ceilingKey(K key);
Map.Entry<K,V> higherEntry(K key);
K higherKey(K key);
Map.Entry<K,V> firstEntry();
Map.Entry<K,V> lastEntry();
Map.Entry<K,V> pollFirstEntry();
Map.Entry<K,V> pollLastEntry();
//返回逆序视图
NavigableMap<K,V> descendingMap();
NavigableSet<K> navigableKeySet();
//逆序key视图
NavigableSet<K> descendingKeySet();
//根据formInclusive判断返图视图是否包含formKey
//根据toInclusive判断返图视图是否包含toKey
NavigableMap<K,V> subMap(K fromKey, boolean fromInclusive,
K toKey, boolean toInclusive);
//根据toInclusive判断返图视图是否包含toKey
NavigableMap<K,V> headMap(K toKey, boolean inclusive);
NavigableMap<K,V> tailMap(K fromKey, boolean inclusive);
SortedMap<K,V> subMap(K fromKey, K toKey);
SortedMap<K,V> headMap(K toKey);
SortedMap<K,V> tailMap(K fromKey);
}
SortMap和SortedMap提供了一些排序需要基本方法。
二、底层
红黑树
恶补这块花费了很久时间。。
理解红黑树的时候有个坑,在这里记录一下:TreeMap中的红黑树叶节点都是空节点,都不存储数据,只要不是叶节点都会存储数据。
三、构造器及常量
//comparator比较器,为null时,按照自然顺序排序
private final Comparator<? super K> comparator;
//根root
private transient Entry<K,V> root = null;
//size
private transient int size = 0;
//多线程是舒勇
private transient int modCount = 0;
//空tree,自然顺序排序
public TreeMap() {
comparator = null;
}
//空tree,通过comparator来比较
public TreeMap(Comparator<? super K> comparator) {
this.comparator = comparator;
}
//tree中m包含entry,entrys按照自然排序重新进行排序,
//运行时间为 n*log(n)。
public TreeMap(Map<? extends K, ? extends V> m) {
comparator = null;
putAll(m);
}
//运行时间n
//生成TreeMap的结构满足平衡二叉树,可能和m的结构不一致
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) {
}
}
//通过递归生成一个平衡二叉树
//生产二叉树的结构:最高层节点颜色都为red,其余black
private void buildFromSorted(int size, Iterator it,
java.io.ObjectInputStream str,
V defaul