系列文章:
前言
TreeMap是基于紅黑樹實現(xiàn)的有序鍵值對集合,排序方法取決于給定的構(gòu)造函數(shù),其系列操作方法如remove,get,put等的時間復(fù)雜度都是O(logn),TreeMap也是非線程安全的,其定義如下:
public class TreeMap<K,V>
extends AbstractMap<K,V>
implements NavigableMap<K,V>, Cloneable, java.io.Serializable
可以看到TreeMap繼承自AbstractMap,實現(xiàn)了NavigableMap接口,支持一系列的導(dǎo)航方法,如返回滿足條件的有序鍵值對集合。
紅黑樹是平衡的二叉排序樹,定義具有五條性質(zhì),關(guān)于紅黑樹的原理及插入,刪除操作,可以見面試舊敵之紅黑樹(直白介紹深入理解)。
繼承關(guān)系
TreeMap繼承關(guān)系
java.lang.Object
|___ java.util.AbstractMap<K,V>
|___ java.util.TreeMap<K,V>
所有已實現(xiàn)的接口:
Serializable, Cloneable, Map<K,V>, NavigableMap<K,V>, SortedMap<K,V>
關(guān)系圖
TreeMap關(guān)系圖
- TreeMap的本質(zhì)是紅黑樹,root是紅黑樹的根節(jié)點
- comparator用來比較key的大小
- size是紅黑樹節(jié)點的個數(shù)
構(gòu)造函數(shù)
// 默認構(gòu)造函數(shù),使用該構(gòu)造函數(shù),則TreeMap按自然排序排列
public TreeMap()
// 帶指定比較器的構(gòu)造函數(shù)
public TreeMap(Comparator<? super K> comparator)
// 創(chuàng)建的TreeMap包含Map
public TreeMap(Map<? extends K, ? extends V> m)
// 創(chuàng)建的TreeMap包含SortedMap
public TreeMap(SortedMap<K, ? extends V> m)
API
Entry<K, V> ceilingEntry(K key)
K ceilingKey(K key)
void clear()
Object clone()
Comparator<? super K> comparator()
boolean containsKey(Object key)
NavigableSet<K> descendingKeySet()
NavigableMap<K, V> descendingMap()
Set<Map.Entry<K, V>> entrySet()
Map.Entry<K, V> firstEntry()
K firstKey()
Map.Entry<K, V> floorEntry(K key)
K floorKey(K key)
V get(Object key)
NavigableMap<K, V> headMap(K tokey, boolean inclusive)
SortedMap<K, V> headMap(K tokey)
Map.Entry<K, V> higherEntry(K key)
K higherKey(K key)
boolean isEmpty()
Set<K> keySet()
Map.Entry<K, V> lastEntry()
K lastKey()
Map.Entry<K, V> lowerEntry(K key)
K lowerKey(K key)
NavigableSet<K> navigableKeySet()
Map.Entry<K, V> pollFirstEntry()
Map.Entry<K, V> pollLastEntry()
V put(K key, V value)
V remove(Object key)
int size()
SortedMap<K, V> subMap(K fromInclusive, K toExclusive)
NavigableMap<K, V> subMap(K fromKey, boolean fromInclusive, K toKey, boolean toInclusive)
NavigableMap<K, V> tailMap(K fromKey, boolean inclusive)
SortedMap<K, V> tailMap(K fromKey)
源碼分析
成員變量
// 比較器,用來排序
private final Comparator<? super K> comparator;
// 根節(jié)點
private transient Entry<K,V> root;
// 紅黑樹節(jié)點總數(shù)
private transient int size = 0;
// 修改次數(shù)
private transient int modCount = 0;
構(gòu)造函數(shù)
// 默認構(gòu)造函數(shù),排序方式用自然排序
public TreeMap() {
comparator = null;
}
// 帶比較器的默認構(gòu)造函數(shù)
public TreeMap(Comparator<? super K> comparator) {
this.comparator = comparator;
}
// 帶Map的構(gòu)造函數(shù)
public TreeMap(Map<? extends K, ? extends V> m) {
comparator = null;
putAll(m);
}
// 帶SortedMap的構(gòu)造函數(shù)
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) {
}
}
buildFromSorted
// 由已排好序的map新建TreeMap
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);
}
// 由已排好序的map新建TreeMap
// 將map中的元素逐個添加到TreeMap中,并返回map的中間元素作為根節(jié)點。
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 {
// 如果high > low 則直接返回
if (hi < lo) return null;
// 獲取中間元素
int mid = (lo + hi) / 2;
Entry<K,V> left = null;
// 若lo小于mid,則遞歸調(diào)用獲取(middle的)左孩子。
if (lo < mid)
left = buildFromSorted(level+1, lo, mid - 1, redLevel,
it, str, defaultVal);
// 獲取middle節(jié)點對應(yīng)的key和value
K key;
V value;
if (it != null) {
if (defaultVal==null) {
Map.Entry<K,V> entry = (Map.Entry<K,V>)it.next();
key = entry.getKey();
value = entry.getValue();
} else {
key = (K)it.next();
value = defaultVal;
}
} else {
key = (K) str.readObject();
value = (defaultVal != null ? defaultVal : (V) str.readObject());
}
// 創(chuàng)建middle節(jié)點
Entry<K,V> middle = new Entry<K,V>(key, value, null);
// 若當(dāng)前節(jié)點的深度=紅色節(jié)點的深度,則將節(jié)點著色為紅色。
if (level == redLevel)
middle.color = RED;
// 設(shè)置middle為left的父親,left為middle的左孩子
if (left != null) {
middle.left = left;
left.parent = middle;
}
if (mid < hi) {
// 遞歸調(diào)用獲取(middle的)右孩子。
Entry<K,V> right = buildFromSorted(level+1, mid+1, hi, redLevel,
it, str, defaultVal);
// 設(shè)置middle為left的父親,left為middle的左孩子
middle.right = right;
right.parent = middle;
}
return middle;
}
增加元素
// 將鍵值對加入TreeMap中
public V put(K key, V value) {
Entry<K,V> t = root;
// 根節(jié)點為空意味著紅黑樹為空
if (t == null) {
compare(key, key); // type (and possibly null) check
// 新建根節(jié)點
root = new Entry<>(key, value, null);
size = 1;
modCount++;
return null;
}
int cmp;
Entry<K,V> parent;
Comparator<? super K> cpr = comparator;
// 在紅黑樹中找到鍵值對插入的位置
// 以key來排序,因此比較key即可
// comparator不為null
if (cpr != null) {
do {
parent = t;
// 比較當(dāng)前節(jié)點key和待插入key間關(guān)系
cmp = cpr.compare(key, t.key);
// cmp小于0,則插入t節(jié)點的左子樹中
if (cmp < 0)
t = t.left;
// cmp大于0,則插入t節(jié)點的右子樹中
else if (cmp > 0)
t = t.right;
// cmp等于0,說明紅黑樹中已有該key,則重設(shè)value
else
return t.setValue(value);
} while (t != null);
}
// 如果comparator為null,則用自然排序方式比較key
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);
}
// 新建待插入的紅黑樹節(jié)點,并返回節(jié)點值
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;
}
// 將map中全部節(jié)點加入TreeMap中
public void putAll(Map<? extends K, ? extends V> map) {
// map大小
int mapSize = map.size();
// 如果TreeMap的大小是0,且map的大小不是0,且map屬于SortMap類型
if (size==0 && mapSize!=0 && map instanceof SortedMap) {
// 判斷map的comparator與當(dāng)前comparator是否相等
// 如果相等則將map中所有元素加入TreeMap中
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;
}
}
// 否則調(diào)用AbstractMap中的putAll方法
// AbstractMap中的putAll方法又會調(diào)用TreeMap的put方法
super.putAll(map);
}
獲取元素
// 獲取key對應(yīng)的value值
public V get(Object key) {
// 獲取key對應(yīng)的節(jié)點p
Entry<K,V> p = getEntry(key);
return (p==null ? null : p.value);
}
// 獲取TreeMap中key對應(yīng)的節(jié)點
final Entry<K,V> getEntry(Object key) {
// 如果comparator不為null,則調(diào)用getEntryUsingComparator()來獲取節(jié)點
if (comparator != null)
return getEntryUsingComparator(key);
if (key == null)
throw new NullPointerException();
// comparator為null,則用自然排序的方式來查找比較
@SuppressWarnings("unchecked")
Comparable<? super K> k = (Comparable<? super K>) key;
Entry<K,V> p = root;
while (p != null) {
int cmp = k.compareTo(p.key);
// cmp小于0,則繼續(xù)遍歷p節(jié)點左子樹
if (cmp < 0)
p = p.left;
// cmp大于0,則繼續(xù)遍歷p節(jié)點右子樹
else if (cmp > 0)
p = p.right;
// cmp等于0,則返回p節(jié)點
else
return p;
}
return null;
}
// 獲取TreeMap中key對應(yīng)的節(jié)點(comparator不為null時)
final Entry<K,V> getEntryUsingComparator(Object key) {
@SuppressWarnings("unchecked")
K k = (K) key;
// comparator不為null,則用comparator方式來比較
Comparator<? super K> cpr = comparator;
if (cpr != null) {
Entry<K,V> p = root;
while (p != null) {
int cmp = cpr.compare(k, p.key);
// cmp小于0,則繼續(xù)遍歷p節(jié)點左子樹
if (cmp < 0)
p = p.left;
// cmp大于0,則繼續(xù)遍歷p節(jié)點右子樹
else if (cmp > 0)
p = p.right;
// cmp等于0,則返回p節(jié)點
else
return p;
}
}
return null;
}
刪除元素
// 刪除TreeMap中的鍵為key的節(jié)點,并返回節(jié)點值
public V remove(Object key) {
// 先獲取鍵為key的節(jié)點
Entry<K,V> p = getEntry(key);
// 節(jié)點為null,則返回null
if (p == null)
return null;
V oldValue = p.value;
// 刪除節(jié)點
deleteEntry(p);
return oldValue;
}
導(dǎo)航方法
返回不小于key的最小節(jié)點
// 返回不小于key的最小鍵值對,沒有則返回null
public Map.Entry<K,V> ceilingEntry(K key) {
return exportEntry(getCeilingEntry(key));
}
// 返回不小于key的最小鍵值對對應(yīng)的key,沒有則返回null
public K ceilingKey(K key) {
return keyOrNull(getCeilingEntry(key));
}
// 獲取TreeMap中不小于key的最小節(jié)點,不存在則返回null
final Entry<K,V> getCeilingEntry(K key) {
// p為根節(jié)點
Entry<K,V> p = root;
while (p != null) {
int cmp = compare(key, p.key);
// 若key < p.key且p存在左子樹,則讓p為p的左子樹
// p不存在左子樹就返回p
if (cmp < 0) {
if (p.left != null)
p = p.left;
else
return p;
} else if (cmp > 0) {
// 若key > p.key且p存在右子樹,則讓p為p的右子樹
if (p.right != null) {
p = p.right;
} else {
// 若p不存在右子樹,則找出p的后繼節(jié)點
// p的后繼節(jié)點有兩種可能,一種是null,另一種是TreeMap中大于key的最小節(jié)點
Entry<K,V> parent = p.parent;
Entry<K,V> ch = p;
// 如果p是p的parent的左孩子,則直接返回p.parent
// 如果p是p的parent的右孩子,則一直向上尋找parent,直到parent為null
while (parent != null && ch == parent.right) {
ch = parent;
parent = parent.parent;
}
return parent;
}
// 如果key == p.key則返回p
} else
return p;
}
return null;
}
// 新建一個AbstractMap.SimpleImmutableEntry類型對象,并返回
// SimpleImmutableEntry實際上是簡化的key-value節(jié)點
static <K,V> Map.Entry<K,V> exportEntry(TreeMap.Entry<K,V> e) {
return (e == null) ? null :
new AbstractMap.SimpleImmutableEntry<>(e);
}
返回不大于key的最大節(jié)點
// 返回不大于key的最大鍵值對,沒有則返回null
public Map.Entry<K,V> floorEntry(K key) {
return exportEntry(getFloorEntry(key));
}
// 返回不大于key的最大的鍵值的KEY,沒有則返回null
public K floorKey(K key) {
return keyOrNull(getFloorEntry(key));
}
// 獲取TreeMap中不大于key的最小節(jié)點,不存在則返回null
// getFloorEntry和getCeilingEntry的原理類似,參照其理解
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的最小的節(jié)點
// 返回大于key的最小鍵值對,沒有則返回null
public Map.Entry<K,V> higherEntry(K key) {
return exportEntry(getHigherEntry(key));
}
// 返回大于key的最小鍵值對的KEY,沒有則返回null
public K higherKey(K key) {
return keyOrNull(getHigherEntry(key));
}
// 獲取TreeMap中大于key的最小節(jié)點,不存在則返回null
// getHigherEntry和getCeilingEntry僅在于不返回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的最大節(jié)點
// 返回小于key的最大的鍵值對,沒有則返回null
public Map.Entry<K,V> lowerEntry(K key) {
return exportEntry(getLowerEntry(key));
}
// 返回小于key的最大的鍵值對所對應(yīng)的KEY,沒有則返回null
public K lowerKey(K key) {
return keyOrNull(getLowerEntry(key));
}
// 獲取TreeMap中小于key的最大節(jié)點,不存在則返回null
// getLowerEntry和getFloorEntry僅在于不返回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;
}
數(shù)據(jù)結(jié)構(gòu)
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; // 節(jié)點顏色
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;
return valEquals(key,e.getKey()) && valEquals(value,e.getValue());
}
// 覆蓋hashCode
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;
}
}
遍歷
假設(shè)key和value
都是String
型
- 根據(jù)
entrySet()
通過Iterator
遍歷
Iterator iter = map.entrySet().iterator();
while(iter.hasNext()){
Map.Entry entry = (Map.Entry)iter.next();
key = (String)entry.getKey();
value = (String)entry.getValue();
}
- 根據(jù)
keySet()
通過Iterator
遍歷
Iterator iter = map.keySet().iterator();
while(iter.hasNext()){
key = (String)iter.next();
value = (String)map.get(key);
}
- 根據(jù)
value()
通過Iterator
遍歷
Iterator iter = map.values().iterator();
while(iter.hasNext()){
value = (String)iter.next;
}