TreeMap的基本用法&實現

TreeMap是使用紅黑樹實現的,他是按鍵有序的。
紅黑樹:從根到葉子節點的路徑,沒有任何一條路徑的長度會比其他路徑長過兩倍。紅黑樹把每個節點進行重色,對節點顏色有一些約束。它確保樹是大致平衡的。

基本構造方法:

/**
* 該方法要求Map中的鍵必須實現Comparable接口,TreeMap進行各種個比較時會調用鍵的Comparable接口中的compareTo方法
*/
	public TreeMap()

	/**
	* 這個構造方法要傳入一個comparator比較器對象,如果comparator不爲null,在TreeMap內部進行比較時會調用這個comparator的comapre方法,而不再調用鍵
	* 的compareTo方法,也不要求鍵實現Comparable接口
	*/
	public TreeMap(Comparator<? super K> comparator)

內部組成

    /**
     * The comparator used to maintain order in this tree map, or
     * null if it uses the natural ordering of its keys.
     *這個 comparator用於維護樹的排序,如果使用key的默認排序則comparator爲null
     * @serial
     */
    private final Comparator<? super K> comparator;

    private transient Entry<K,V> root; // 指向樹的根節點

    /**
     * The number of entries in the tree
     * 樹中鍵值對的個數
     */
    private transient int size = 0;

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;

        /**
         * Make a new cell with given key, value, and parent, and with
         * {@code null} child links, and BLACK color.
         */
        Entry(K key, V value, Entry<K,V> parent) {
            this.key = key;
            this.value = value;
            this.parent = parent;
        }
    }

每個節點除了鍵和值之外,還有三個引用,分別爲左、右孩子,以及父節點。
color表示顏色,默認爲黑。

方法詳解

1.put

    /**
     * Associates the specified value with the specified key in this map.
     * 將制定的值與指定的鍵在map中做關聯
     * If the map previously contained a mapping for the key, the old
     * 如果以前這個key在map中存在,那麼舊值會被取代
     * value is replaced.
     *
     * @param key key with which the specified value is to be associated
     * @param value value to be associated with the specified key
     *
     * @return the previous value associated with {@code key}, or
     *         {@code null} if there was no mapping for {@code key}.
     *         (A {@code null} return can also indicate that the map
     *         previously associated {@code null} with {@code key}.)
     * @throws ClassCastException if the specified key cannot be compared
     *         with the keys currently in the map
     * @throws NullPointerException if the specified key is null
     *         and this map uses natural ordering, or its comparator
     *         does not permit null keys
     */
    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;
    }

代碼比較長,我們分段來看:

  1. 第一次添加的判斷:
  public V put(K key, V value) {
        Entry<K,V> t = root;
        if (t == null) {
            compare(key, key); // type (and possibly null) check : 類型和null檢查

            root = new Entry<>(key, value, null);
            size = 1;
            modCount++;
            return null;
        }

首先判斷根節點是否爲null,如果爲空,說明是第一次添加,則把新傳入的鍵值節點設爲根節點。然後size+1,modCount
用於記錄修改次數
使用modCount屬性的全是線程不安全的,關於modCount的解釋可以參考這篇博文modCount到底是幹什麼的呢

其中比較奇怪的是一段類型和null檢查的代碼:compare(key, key),比較key和key有什麼意思呢?


    /**
     * Compares two keys using the correct comparison method for this TreeMap.
     * 使用這個TreeMap的比較方法比較兩個key
     */
    @SuppressWarnings("unchecked")
    final int compare(Object k1, Object k2) {
    // 如果comparator對象爲null則使用key的compareTo方法進行比較,不爲null則使用comparator的compare比較哦
        return comparator==null ? ((Comparable<? super K>)k1).compareTo((K)k2)
            : comparator.compare((K)k1, (K)k2);
    }

還是不太懂這段代碼是什麼意思,注意put方法中調用compare方法時的註釋:類型和null檢查;
這裏主要是爲了檢查key是否實現Comparable接口或者是否爲null——即檢查key是否符合TreeMap的要求

  1. 尋找新put鍵值對的父節點
    尋找鍵值對父節點的時候分兩種情況,使用key自身的比較器或者使用初始化TreeMap時傳入的比較器
    2.1. 設置了comparator比較器:
		int cmp;
        Entry<K,V> parent;
        // split comparator and comparable paths
        Comparator<? super K> cpr = comparator;
        if (cpr != null) {
            do {
                parent = t; // 第一次執行這一步時,t是根節點
                cmp = cpr.compare(key, t.key);
                if (cmp < 0) // key小於根節點的
                    t = t.left; // 把t改爲當前節點的左孩子,因爲左孩子小於父節點
                else if (cmp > 0) // key大於根節點
                    t = t.right; // 把t改爲當前節點的右孩子
                else // 說明跟當前節點key值,相等
                    return t.setValue(value);
            } while (t != null); // 當退出循環時parent指向待插入節點的父節點
        }
2.2. 沒有設置comparator比較器
	        else {
            if (key == null)
                throw new NullPointerException();
            @SuppressWarnings("unchecked")
                Comparable<? super K> k = (Comparable<? super K>) key; // 如果key
            do {
                parent = t;
                cmp = k.compareTo(t.key);
                if (cmp < 0) // key小於當前節點
                    t = t.left;
                else if (cmp > 0) // key大於當前節點
                    t = t.right;
                else
                    return t.setValue(value);
            } while (t != null);
        }

Comparable可以認爲是一個內比較器,實現了Comparable接口的類有一個特點,就是這些類是可以和自己比較的,至於具體和另一個實現了Comparable接口的類如何比較,則依賴compareTo方法的實現,compareTo方法也被稱爲自然比較方法。
Comparator可以認爲是是一個外比較器,個人認爲有兩種情況可以使用實現Comparator接口的方式:
1、一個對象不支持自己和自己比較(沒有實現Comparable接口),但是又想對兩個對象進行比較
2、一個對象實現了Comparable接口,但是開發者認爲compareTo方法中的比較方式並不是自己想要的那種比較方式
引用自:Comparable和Comparator的區別

  1. 新建節點
    找到父節點後,新建一個節點掛在父節點上,掛之前判斷是左孩子還是右孩子,並增加size和modCount
		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;
    }

其中fixAfterInsertion方法,調整樹的結構,使之符合紅黑樹約束,保持大致平衡,這裏就不深入探討了。

2. get

上代碼:

    public V get(Object key) {
        Entry<K,V> p = getEntry(key);
        return (p==null ? null : p.value);
    }

get方法就不多說了,是老鐵都明白。
getEntry方法:

    
final Entry<K,V> getEntry(Object key) {
        // Offload comparator-based version for sake of performance
        // 同樣分是否傳入了comparator對象兩種情況
        if (comparator != null) 
            return getEntryUsingComparator(key);
        if (key == null)
            throw new NullPointerException();
        @SuppressWarnings("unchecked")
            Comparable<? super K> k = (Comparable<? super K>) key;
        Entry<K,V> p = root;
        while (p != null) {
            int cmp = k.compareTo(p.key);
            if (cmp < 0)
                p = p.left;
            else if (cmp > 0)
                p = p.right;
            else
                return p;
        }
        return null;
    }

跟put方法很類似,如果comparator不爲空,則調用單獨的方法getEntryUsingComparator,否則假定key實現了Comparable接口,使用compareTo進行比較
找的邏輯跟put一樣,從根開始找,比根小,往左找;比根大,往右找,找到爲止,如果沒有找到,返回null;。getEntryUsingComparator方法的邏輯類似,就不多說了。

3. containsValue

TreeMap可以根據鍵高效的進行查找,但是如果根據值進行查找,則需要遍歷,上代碼:

    public boolean containsValue(Object value) {
    // getFirstEntry獲取第一個點(key最小)
    // successor獲取給定節點的後繼節點
        for (Entry<K,V> e = getFirstEntry(); e != null; e = successor(e))
            if (valEquals(value, e.value)) // valEquals比較值是否相等
                return true;
        return false;
    }

getFirstEntry:

    final Entry<K,V> getFirstEntry() {
        Entry<K,V> p = root;
        if (p != null)
            while (p.left != null)
                p = p.left;
        return p;
    }

successor:

    static <K,V> TreeMap.Entry<K,V> successor(Entry<K,V> t) {
        if (t == null)
            return null;
        else if (t.right != null) {  // 右子節點不爲null則找右子節點下的最左側節點
            Entry<K,V> p = t.right;
            while (p.left != null)
                p = p.left;
            return p;
        } else { // 右子節點爲null
            Entry<K,V> p = t.parent;
            Entry<K,V> ch = t;
            while (p != null && ch == p.right) { // 父節點不爲null且當前節點是父節點的右孩子
                ch = p;
                p = p.parent;
            }
            return p; // 如果當前節點父節點是左孩子或者爲null,則返回父節點
        }
    }

其實只要知道二叉樹是如何找後繼節點,這段代碼就很好懂;
這裏畫蛇添足增加一下文案描述:

  1. 如果當前節點有右節點則找到右子樹中最小的節點(最左下的節點)
  2. 如果當前節點沒有右節點,那麼其後繼節有三種情況
    2.1 :當前節點是父節點的右孩子,那麼後繼節點一定是當前節點的某一個祖先節點;一直往上找父,直到父是爺爺的左子樹,那麼返回爺爺,比較抽象,建議大家畫個圖,一目瞭然。
    2.2 :當前節點是父節點的左孩子,那麼後繼節點就是父節點
    2.3 :當前節點無後繼節點,返回null

4. remove

    public V remove(Object key) {
        Entry<K,V> p = getEntry(key);
        if (p == null)
            return null;

        V oldValue = p.value;
        deleteEntry(p);
        return oldValue;
    }

調用getEntry獲取要刪除的節點;
如果存在那麼調用deleteEntry方法刪除,返回節點值。
deleteEntry:

   /**
     * Delete node p, and then rebalance the tree.
     * 刪掉p,然後平衡樹 
     */
    private void deleteEntry(Entry<K,V> p) {
        modCount++; // 變更記錄+1
        size--; // 大小-1

        // 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指向後繼節點
        } // 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;
            }
        }
    }

刪除這部分不太好理解,建議我們先在紙上自己畫一下二叉樹刪除的幾種情況:

  1. 葉子節點,這個容易處理,直接修改父節點的對應引用位置爲null即可
  2. 只有一個孩子:在父節點和孩子節點之間建立連接。
  3. 有兩個孩子:這個就複雜一點了,首先,找到後繼節點,找到後替換當前節點爲後繼節點,然後再刪除後繼節點,因爲後繼節點肯定沒有左孩子,這樣就把兩個孩子的情況轉換爲了前面兩種情況(可以理解爲把要刪除的節點替換爲後繼節點,然後再處理後繼節點下的樹)

我們拆開來看:畫圖更好理解!!

  1. 兩個子節點的情況, 把要刪除的節點替換爲後繼節點,然後刪除後繼節點,轉換爲前兩種情況
    private void deleteEntry(Entry<K,V> p) {
        modCount++; // 變更記錄+1
        size--; // 大小-1

        // 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

  1. 一個子節點的情況:
        // Start fixup at replacement node, if it exists.
        Entry<K,V> replacement = (p.left != null ? p.left : p.right); // p爲待刪除節點,找到替換p節點的孩子節點,找不到爲null

        if (replacement != null) { // 孩子節點不爲null
            // Link replacement to parent
            replacement.parent = p.parent; // 把孩子節點的父節點改爲要刪除節點的父節點
            if (p.parent == null) // 如果要刪除節點的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.
            // 將要刪除節點的左右和父都職位null,然後使用平衡方法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.——沒有孩子節點也沒有父節點
  1. 最後一段: 無子節點——葉子節點的情況
        } 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) // 如果要刪除的節點爲父的左節點,設置父的左孩子爲null
                    p.parent.left = null;
                else if (p == p.parent.right) 如果要刪除的節點爲父的右節點,設置父的右孩子爲null
                    p.parent.right = null;
                p.parent = null; // 因爲是葉子節點,只把要刪除節點的父置爲null;
            }
        }
    }

小結

與HashMap相比,TreeMap同樣實現了Map接口,但內部使用紅黑樹實現。紅黑樹是統計效率比較高的大致平衡二叉樹,這決定了它有如下特點:

  1. 按鍵有序,TreeMap同樣實現了NavigableMap接口(該接口實現了SortedMap接口)可以方便地根據鍵的順序進行查找,如第一個、最後一個、某一範圍的鍵、鄰近鍵等。
  2. 爲了按鍵有序,TreeMap要求鍵實現Comparable接口或通過構造方法提供一個Comparator對象。
  3. 根據鍵保存、查找、刪除的效率比較高,爲O(h),h爲樹的高度,在樹平衡的情況下,h爲log(N),N爲節點數。

應該使用TreeMap還是HashMap呢?不要求排序優先考慮HashMap,要求排序,考慮TreeMap。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章