基於源碼的Java集合框架學習⑬ TreeMap

類 TreeMap<K,V>

SortedMap 接口的基於紅黑樹的實現。此類保證了映射按照升序順序排列關鍵字,根據使用的構造方法不同,可能會按照鍵的類的自然順序 進行排序(參見 Comparable),或者按照創建時所提供的比較器進行排序。

此實現爲 containsKey、get、put 和 remove 操作提供了保證的 log(n) 時間開銷。這些算法是 Cormen、Leiserson 和 Rivest 的《Introduction to Algorithms》中的算法的改編。

如果有序映射要正確實現 Map 接口,則有序映射所保持的順序(無論是否明確提供比較器)都必須保持與等號一致。(請參見與等號一致 的精確定義的 Comparable 或 Comparator。)這也是因爲 Map 接口是按照等號操作定義的,但映射使用它的 compareTo(或 compare)方法對所有鍵進行比較,因此從有序映射的觀點來看,此方法認爲相等的兩個鍵就是相等的。即使順序與等號不一致,有序映射的行爲仍然是 定義良好的;只不過沒有遵守 Map 接口的常規約定。

此實現不是同步的。

源碼

構造方法:

    // 排序用的比較器
    // 默認使用鍵的自然順序
    private final Comparator<? super K> comparator;
    // 根節點
    private transient Entry<K,V> root = null;
    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) {
        }
    }
    // 根據已經一個排好序的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);
    }
    // 計算節點樹爲sz的最大深度,也是紅色節點的深度值。
    private static int computeRedLevel(int sz) {
        int level = 0;
        for (int m = sz - 1; m >= 0; m = m / 2 - 1)
            level++;
        return level;
    }
    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 {
        /*
         * Strategy: The root is the middlemost element. To get to it, we
         * have to first recursively construct the entire left subtree,
         * so as to grab all of its elements. We can then proceed with right
         * subtree.
         *
         * The lo and hi arguments are the minimum and maximum
         * indices to pull out of the iterator or stream for current subtree.
         * They are not actually indexed, we just proceed sequentially,
         * ensuring that items are extracted in corresponding order.
         */

        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<K,V> entry = (Map.Entry<K,V>)it.next();
                key = entry.getKey();
                value = 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;
    }

Entry的結構:(紅黑樹)

    private static final boolean RED   = false;
    private static final boolean BLACK = true;
    
    static final class Entry<K,V> implements Map.Entry<K,V> {
        K key;
        V value;
        Entry<K,V> left = null;
        Entry<K,V> right = null;
        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;
        }

        /**
         * Returns the key.
         *
         * @return the key
         */
        public K getKey() {
            return key;
        }

        /**
         * Returns the value associated with the key.
         *
         * @return the value associated with the key
         */
        public V getValue() {
            return value;
        }

        /**
         * Replaces the value currently associated with the key with the given
         * value.
         *
         * @return the value associated with the key before this method was
         *         called
         */
        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());
        }

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

get方法:

    public V get(Object key) {
        Entry<K,V> p = getEntry(key);
        return (p==null ? null : p.value);
    }
    
    final Entry<K,V> getEntry(Object key) {
        // Offload comparator-based version for sake of performance
        // 是否指定了比較器
        if (comparator != null)
            return getEntryUsingComparator(key);
        if (key == null)
            throw new NullPointerException();
        Comparable<? super K> k = (Comparable<? super K>) key;
        Entry<K,V> p = root;
        while (p != null) {
        	// 循環直至葉子節點或者獲取到key相等的節點
        	// 判斷key位於左子樹還是右子樹
            int cmp = k.compareTo(p.key);
            if (cmp < 0)
                p = p.left;
            else if (cmp > 0)
                p = p.right;
            else
                return p;
        }
        return null;
    }
    final Entry<K,V> getEntryUsingComparator(Object key) {
        K k = (K) key;
        Comparator<? super K> cpr = comparator;
        if (cpr != null) {
            Entry<K,V> p = root;
            while (p != null) {
                int cmp = cpr.compare(k, p.key);
                if (cmp < 0)
                    p = p.left;
                else if (cmp > 0)
                    p = p.right;
                else
                    return p;
            }
        }
        return null;
    }

put方法:

   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;
        // 存在該KEY則更新
        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();
            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);
        }
        // 不存在該KEY,則新增節點
        // 上面的循環中其實已經找到了新增節點的父節點
        Entry<K,V> e = new Entry<>(key, value, parent);
        if (cmp < 0)
            parent.left = e;
        else
            parent.right = e;
        // 這裏通過fixAfterInsertion的處理,來恢復紅黑樹的特性。
        fixAfterInsertion(e);
        size++;
        modCount++;
        return null;
    }

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

總結

TreeMap基於紅黑樹(Red-Black tree)實現。該映射根據其鍵的自然順序進行排序,或者根據創建映射時提供的 Comparator 進行排序,具體取決於使用的構造方法。

TreeMap的基本操作 containsKey、get、put 和 remove 的時間複雜度是 log(n) 。

TreeMap是非同步的。

它的iterator 方法返回的迭代器是fail-fastl的。

參考

TreeMap:http://www.cnblogs.com/skywang12345/p/3310928.html
紅黑樹:http://blog.jobbole.com/111680/

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