Java集合系列09之TreeMap源碼分析

系列文章

前言

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;
}

參考信息

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。
  • 序言:七十年代末,一起剝皮案震驚了整個濱河市,隨后出現(xiàn)的幾起案子,更是在濱河造成了極大的恐慌,老刑警劉巖,帶你破解...
    沈念sama閱讀 230,321評論 6 543
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件,死亡現(xiàn)場離奇詭異,居然都是意外死亡,警方通過查閱死者的電腦和手機,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 99,559評論 3 429
  • 文/潘曉璐 我一進店門,熙熙樓的掌柜王于貴愁眉苦臉地迎上來,“玉大人,你說我怎么就攤上這事。” “怎么了?”我有些...
    開封第一講書人閱讀 178,442評論 0 383
  • 文/不壞的土叔 我叫張陵,是天一觀的道長。 經(jīng)常有香客問我,道長,這世上最難降的妖魔是什么? 我笑而不...
    開封第一講書人閱讀 63,835評論 1 317
  • 正文 為了忘掉前任,我火速辦了婚禮,結(jié)果婚禮上,老公的妹妹穿的比我還像新娘。我一直安慰自己,他們只是感情好,可當(dāng)我...
    茶點故事閱讀 72,581評論 6 412
  • 文/花漫 我一把揭開白布。 她就那樣靜靜地躺著,像睡著了一般。 火紅的嫁衣襯著肌膚如雪。 梳的紋絲不亂的頭發(fā)上,一...
    開封第一講書人閱讀 55,922評論 1 328
  • 那天,我揣著相機與錄音,去河邊找鬼。 笑死,一個胖子當(dāng)著我的面吹牛,可吹牛的內(nèi)容都是我干的。 我是一名探鬼主播,決...
    沈念sama閱讀 43,931評論 3 447
  • 文/蒼蘭香墨 我猛地睜開眼,長吁一口氣:“原來是場噩夢啊……” “哼!你這毒婦竟也來了?” 一聲冷哼從身側(cè)響起,我...
    開封第一講書人閱讀 43,096評論 0 290
  • 序言:老撾萬榮一對情侶失蹤,失蹤者是張志新(化名)和其女友劉穎,沒想到半個月后,有當(dāng)?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體,經(jīng)...
    沈念sama閱讀 49,639評論 1 336
  • 正文 獨居荒郊野嶺守林人離奇死亡,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點故事閱讀 41,374評論 3 358
  • 正文 我和宋清朗相戀三年,在試婚紗的時候發(fā)現(xiàn)自己被綠了。 大學(xué)時的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片。...
    茶點故事閱讀 43,591評論 1 374
  • 序言:一個原本活蹦亂跳的男人離奇死亡,死狀恐怖,靈堂內(nèi)的尸體忽然破棺而出,到底是詐尸還是另有隱情,我是刑警寧澤,帶...
    沈念sama閱讀 39,104評論 5 364
  • 正文 年R本政府宣布,位于F島的核電站,受9級特大地震影響,放射性物質(zhì)發(fā)生泄漏。R本人自食惡果不足惜,卻給世界環(huán)境...
    茶點故事閱讀 44,789評論 3 349
  • 文/蒙蒙 一、第九天 我趴在偏房一處隱蔽的房頂上張望。 院中可真熱鬧,春花似錦、人聲如沸。這莊子的主人今日做“春日...
    開封第一講書人閱讀 35,196評論 0 28
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽。三九已至,卻和暖如春,著一層夾襖步出監(jiān)牢的瞬間,已是汗流浹背。 一陣腳步聲響...
    開封第一講書人閱讀 36,524評論 1 295
  • 我被黑心中介騙來泰國打工, 沒想到剛下飛機就差點兒被人妖公主榨干…… 1. 我叫王不留,地道東北人。 一個月前我還...
    沈念sama閱讀 52,322評論 3 400
  • 正文 我出身青樓,卻偏偏與公主長得像,于是被迫代替她去往敵國和親。 傳聞我的和親對象是個殘疾皇子,可洞房花燭夜當(dāng)晚...
    茶點故事閱讀 48,554評論 2 379

推薦閱讀更多精彩內(nèi)容