成員變量:
private final Comparator<? super K> comparator;
private transient Entry<K,V> root;
private transient int size = 0;
private transient int modCount = 0;
private transient EntrySet entrySet;
private transient KeySet<K> navigableKeySet;
private transient NavigableMap<K,V> descendingMap;
private static final Object UNBOUNDED = new Object();
private static final boolean RED = false;
private static final boolean BLACK = true;
可以看出有一個排序器變量comparator断楷,可以知道TreeMap是可以排序的(默認自然排序票腰,或者自定義排序)扼菠。
節(jié)點類TreeMap.Entry:
static final class Entry<K,V> implements Map.Entry<K,V> {
K key;
V value;
Entry<K,V> left;
Entry<K,V> right;
Entry<K,V> parent;
boolean color = BLACK;
Entry(K key, V value, Entry<K,V> parent) {
this.key = key;
this.value = value;
this.parent = parent;
}
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());
}
public int hashCode() {
int keyHash = (key==null ? 0 : key.hashCode());
int valueHash = (value==null ? 0 : value.hashCode());
return keyHash ^ valueHash;
}
}
從節(jié)點類我們可以看出TreeMap的數(shù)據(jù)結(jié)構(gòu)是基于紅黑樹的奈梳,關于紅黑樹可以看下我的這篇文章紅黑樹砚蓬。
TreeMap提供四個構(gòu)造器:
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) {
comparator = m.comparator();
try {
buildFromSorted(m.size(), m.entrySet().iterator(), null, null);
} catch (java.io.IOException cannotHappen) {
} catch (ClassNotFoundException cannotHappen) {
}
}
第三個構(gòu)造器調(diào)用putAll,第四個構(gòu)造器調(diào)用buildFromSorted膝迎,看下putAll源碼先 :
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);
}
可以看出粥帚,putAll里的兩個if條件也是試圖調(diào)用buildFromSorted方法然后直接return,不滿足這兩個if就調(diào)用super.putAll(map)限次,那么buildFromSorted究竟干啥的芒涡?別慌,先把這兩個if條件搞明白先卖漫。這兩個if條件表示:
- 當前紅黑樹是空的
- 要插入的集合必須是有排序的即實現(xiàn)SortedMap接口
- 紅黑樹的排序器comparator和要插入的集合的排序器是相同的
解釋了這兩個if條件费尽,你應該能明白buildFromSorted是干啥了的吧?沒錯羊始,就是用來初始化紅黑樹的旱幼。調(diào)用super.putAll(map)會循環(huán)調(diào)用put方法,put方法里判斷紅黑樹根節(jié)點root是nil的話也會初始化紅黑樹突委,為啥直接調(diào)用buildFromSorted而跳過了super.putAll(map)呢柏卤?我之前分析紅黑樹的文章里有提過,紅黑樹的put操作時間復雜度是匀油,再加上外層的循環(huán)缘缚,那么super.putAll(map)時間復雜度就是
,那么我們來分析下buildFromSorted的時間復雜度吧敌蚜,看下buildFromSorted的源碼:(JDK的作者真是性能優(yōu)化到牙齒)
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);
}
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);
// 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;
}
我不知道怎么把簡書文章里的代碼顯示行數(shù)桥滨,湊合著解釋吧藤韵。假設有序的map集合是椒振,那么lo=0埠胖,hi=8准夷,mid=4瓣戚,以mid為根節(jié)點middle鸳兽,將原來的集合分成兩個子樹left和right锅睛,分別作為根節(jié)點middle的左子樹和右子樹煌茴,
忽舟,
双妨,再在兩個子樹上遞歸調(diào)用buildFromSorted方法,這樣就構(gòu)成了一棵樹叮阅。
從上面的節(jié)點類TreeMap.Entry我們知道刁品,節(jié)點的默認顏色是黑色,那么我們這棵樹的所有節(jié)點顏色都是黑色浩姥,這棵樹肯定滿足紅黑樹的1挑随、2、3勒叠、4性質(zhì)(不清楚紅黑樹5條性質(zhì)的話可以看下我的這篇文章紅黑樹)兜挨,但是不一定滿足性質(zhì)5膏孟,當且僅當這棵樹是滿二叉樹的時候才滿足性質(zhì)5,怎么辦呢拌汇?我們對這棵樹進行著色就好了柒桑。怎么著色呢?只需要把樹的最底層的節(jié)點全部變成紅色就行了噪舀,簡單吧魁淳?而方法computeRedLevel
就是計算樹的最底層數(shù),如果一個節(jié)點的層數(shù)
与倡,表示節(jié)點處于最底層界逛,就染成紅色,看下
computeRedLevel
源碼:
private static int computeRedLevel(int sz) {
int level = 0;
for (int m = sz - 1; m >= 0; m = m / 2 - 1)
level++;
return level;
}
剛開始分析這個變量時有點暈蒸走,以為是樹的高度
仇奶,但是
是從0開始計算的,而樹的高度
是從1開始計算的比驻。
這樣我們就成功構(gòu)造了一個紅黑樹该溯,我們很清晰的知道這個步驟的時間復雜度是,而super.putAll(map)時間復雜度是
别惦,這就是優(yōu)先調(diào)用
buildFromSorted
的原因狈茉。
public V put(K key, V value) {
Entry<K,V> t = root;
if (t == 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
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;
}
由于紅黑樹是基于二叉排序樹的,所以插入也是基于二叉排序樹的掸掸,即:從根節(jié)點開始氯庆,遇鍵值較大者就向左,遇鍵值較小者就向右扰付,一直到末端堤撵,就是插入點。
- 第一個條件if最簡單羽莺,但是執(zhí)行compare(key, key)是什么意思呀实昨?我真搞不懂,求解釋盐固;
- 第一個條件if表示root不為nil并且排序器comparator不為nil荒给,這和二叉排序樹的算法一模一樣,不解釋了刁卜;
- 第三個條件else表示root不為nil并且排序器comparator為nil志电,那么就用自然排序,這和二叉排序樹的算法一模一樣蛔趴,不解釋了挑辆;
- 第四個條件if和else是進行插入操作;
- 插入完可能破壞紅黑樹的性質(zhì),進行修正操作fixAfterInsertion之拨。
修正操作(左旋茉继、右旋、變色)是一個很有技術含量的過程蚀乔,我就不解釋了,具體看我的這篇文章:紅黑樹菲茬。
public V remove(Object key) {
Entry<K,V> p = getEntry(key);
if (p == null)
return null;
V oldValue = p.value;
deleteEntry(p);
return oldValue;
}
private void deleteEntry(Entry<K,V> p) {
modCount++;
size--;
// If strictly internal, copy successor's element to p and then make p
// point to successor.
if (p.left != null && p.right != null) {
Entry<K,V> s = successor(p);
p.key = s.key;
p.value = s.value;
p = s;
} // p has 2 children
// Start fixup at replacement node, if it exists.
Entry<K,V> replacement = (p.left != null ? p.left : p.right);
if (replacement != null) {
// Link replacement to parent
replacement.parent = p.parent;
if (p.parent == null)
root = replacement;
else if (p == p.parent.left)
p.parent.left = replacement;
else
p.parent.right = replacement;
// Null out links so they are OK to use by fixAfterDeletion.
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.
root = null;
} else { // No children. Use self as phantom replacement and unlink.
if (p.color == BLACK)
fixAfterDeletion(p);
if (p.parent != null) {
if (p == p.parent.left)
p.parent.left = null;
else if (p == p.parent.right)
p.parent.right = null;
p.parent = null;
}
}
}
private void fixAfterDeletion(Entry<K,V> x) {
while (x != root && colorOf(x) == BLACK) {
if (x == leftOf(parentOf(x))) {
Entry<K,V> sib = rightOf(parentOf(x));
if (colorOf(sib) == RED) {
setColor(sib, BLACK);
setColor(parentOf(x), RED);
rotateLeft(parentOf(x));
sib = rightOf(parentOf(x));
}
if (colorOf(leftOf(sib)) == BLACK &&
colorOf(rightOf(sib)) == BLACK) {
setColor(sib, RED);
x = parentOf(x);
} else {
if (colorOf(rightOf(sib)) == BLACK) {
setColor(leftOf(sib), BLACK);
setColor(sib, RED);
rotateRight(sib);
sib = rightOf(parentOf(x));
}
setColor(sib, colorOf(parentOf(x)));
setColor(parentOf(x), BLACK);
setColor(rightOf(sib), BLACK);
rotateLeft(parentOf(x));
x = root;
}
} else { // symmetric
Entry<K,V> sib = leftOf(parentOf(x));
if (colorOf(sib) == RED) {
setColor(sib, BLACK);
setColor(parentOf(x), RED);
rotateRight(parentOf(x));
sib = leftOf(parentOf(x));
}
if (colorOf(rightOf(sib)) == BLACK &&
colorOf(leftOf(sib)) == BLACK) {
setColor(sib, RED);
x = parentOf(x);
} else {
if (colorOf(leftOf(sib)) == BLACK) {
setColor(rightOf(sib), BLACK);
setColor(sib, RED);
rotateLeft(sib);
sib = leftOf(parentOf(x));
}
setColor(sib, colorOf(parentOf(x)));
setColor(parentOf(x), BLACK);
setColor(leftOf(sib), BLACK);
rotateRight(parentOf(x));
x = root;
}
}
}
setColor(x, BLACK);
}
這個刪除包括兩步:刪除和修正吉挣,這里不解釋了,具體流程看我的這篇文章:紅黑樹婉弹。
TreeMap提供了三個迭代器進行遍歷KeyIterator睬魂、ValueIterator、EntryIterator镀赌,這三個迭代器有一個共同的基類:PrivateEntryIterator氯哮,所以遍歷操作都是PrivateEntryIterator操作的,
看下PrivateEntryIterator的構(gòu)造器:
PrivateEntryIterator(Entry<K,V> first) {
expectedModCount = modCount;
lastReturned = null;
next = first;
}
注意first這個參數(shù)并不是root節(jié)點商佛,看下生成first的方法:
final Entry<K,V> getFirstEntry() {
Entry<K,V> p = root;
if (p != null)
while (p.left != null)
p = p.left;
return p;
}
可以看到迭代器保存的第一個節(jié)點next是樹的最左邊的節(jié)點而不是root節(jié)點喉钢,清楚這一點,那么我們分析迭代器的核心方法nextEntry
就簡單一些了:
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;
}
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;
}
}
一般的紅黑樹提供了中序遍歷良姆、前序遍歷肠虽、后序遍歷三種方法,而且是使用遞歸實現(xiàn)的玛追,但是上面的代碼是使用性能更優(yōu)的while循環(huán)操作税课,這樣避免了遞歸可能導致的OOM問題。
- 第一個條件if不解釋
- 第二個條件elseif表示試圖找到當前節(jié)點t的右子樹最左邊的節(jié)點痊剖,如果找不到就返回右孩子韩玩,表示當前節(jié)點的下一個節(jié)點優(yōu)先是右子樹最左邊的節(jié)點,其次是右孩子
- 第三個條件else表示從當前節(jié)點t開始從右下向左上遍歷一條斜線陆馁,ch表示斜線的頂點找颓,p表示ch的父節(jié)點,這么可以肯定的是這條斜線肯定掛載在p的左子樹上氮惯,意味著肯定是先遍歷完一個節(jié)點的左子樹再遍歷這個節(jié)點自己叮雳,根據(jù)上一步驟的判斷,最后遍歷右子樹妇汗。
根據(jù)上面三個步驟的分析帘不,我們有理由猜測,successor
方法就是二叉排序樹中序遍歷的while循環(huán)版本杨箭,而二叉排序樹的中序遍歷就是從小到大的自然排序寞焙,由于TreeMap可能有自己的排序器conparator,那么中序遍歷的結(jié)果就是排序器的結(jié)果。
在分析TreeMap的遍歷源碼之前捣郊,我還不知道怎么使用while循環(huán)實現(xiàn)中序遍歷辽狈,遞歸雖簡單但是可能會棧溢出StackOverflowError,每個方法被執(zhí)行的時候都會同時創(chuàng)建一個棧幀(Stack Frame)用于存儲局部變量表呛牲、操作棧刮萌、動態(tài)鏈接、方法出口等信息娘扩,每一個方法被調(diào)用直至執(zhí)行完成的過程着茸,就對應著一個棧幀在虛擬機棧中從入棧到出棧的過程,如果棧深度大于虛擬機所允許的深度琐旁,將拋出StackOverflowError異常涮阔;如果虛擬機棧可以動態(tài)擴展(當前大部分的Java虛擬機都可動態(tài)擴展灰殴,只不過Java虛擬機規(guī)范中也允許固定長度的虛擬機棧)敬特,當擴展時無法申請到足夠的內(nèi)存時會拋出OutOfMemoryError異常∥眨看了源碼感覺新的裝逼技能get到伟阔。
由于TreeMap基于紅黑樹實現(xiàn)的,時間復雜度平均能達到义图。我的這篇文章Java集合源碼分析-HashMap和IdentityHashMap分析了HashMap的時間復雜度得知平均能達到
减俏,那么集合不需要排序的話首選HashMap這個類,如果需要排序就只能用TreeMap了碱工。