国产成人精品18p,天天干成人网,无码专区狠狠躁天天躁,美女脱精光隐私扒开免费观看

Java基礎之TreeMap詳解

發(fā)布時(shí)間:2021-07-17 21:51 來(lái)源:腳本之家 閱讀:0 作者:伏城之外 欄目: 編程語(yǔ)言 歡迎投稿:712375056

目錄

一、寫(xiě)在前面

TreeMap的底層數據結構是紅黑樹(shù),且TreeMap可以實(shí)現集合元素的排序。

所以TreeMap的源碼需要實(shí)現:

1.紅黑樹(shù)的數據結構,以及紅黑樹(shù)的節點(diǎn)插入,刪除,以及紅黑樹(shù)的自平衡操作,如左旋,右旋,以及節點(diǎn)變色

2.紅黑樹(shù)需要支持按照指定的比較器進(jìn)行排序,或者進(jìn)行自然排序。

二、定義

public class TreeMap<K,V>
    extends AbstractMap<K,V>
    implements NavigableMap<K,V>, Cloneable, java.io.Serializable
public interface NavigableMap<K,V> extends SortedMap<K,V> {

TreeMap

繼承了AbstractMap

實(shí)現了NavigableMap,而NavigableMap接口繼承了SortedMap接口,SortedMap接口表示其實(shí)現類(lèi)是一個(gè)有序集合

實(shí)現了Cloneable,所以支持對象克隆

實(shí)現了Serializable,所以支持對象序列化

三、成員變量

comparator

 /**
     * The comparator used to maintain order in this tree map, or
     * null if it uses the natural ordering of its keys.
     *
     * @serial
     */
    private final Comparator<? super K> comparator;

外部指定的比較器。在創(chuàng )建TreeMap對象時(shí)可以指定。如果指定了比較器,則TreeMap插入鍵值對時(shí),按照comparator比較排序。 

root

 private transient Entry<K,V> root;

root指代TreeMap底層紅黑樹(shù)的根節點(diǎn)。 root的類(lèi)型Entry<K,V>就是紅黑樹(shù)節點(diǎn)的類(lèi)型。

紅黑樹(shù)數據結構的實(shí)現就依賴(lài)于Entry<K,V>

size

/**
     * The number of entries in the tree
     */
    private transient int size = 0;

 表示TreeMap集合中鍵值對個(gè)數。

modCount 

/**
     * The number of structural modifications to the tree.
     */
    private transient int modCount = 0;

表示TreeMap集合被結構化修改的次數。用于迭代器迭代過(guò)程中檢測集合是否被結構化修改,若是,則fail-fast。

四、內部類(lèi)

Entry<K,V>

Entry<K,V>是紅黑樹(shù)節點(diǎn)的代碼實(shí)現,是實(shí)現紅黑樹(shù)數據結構的基礎。

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

成員變量 

K key,V value分別是TreeMap集合中存儲的鍵值對的鍵和值

Entry<K,V> left 代表當前節點(diǎn)的左子節點(diǎn)

Entry<K,V> right 代表當前節點(diǎn)的右子節點(diǎn)

Entry<K,V> parent 代表當前節點(diǎn)的父節點(diǎn)

boolean color 代表當前節點(diǎn)的顏色,默認是黑色,為true

構造器

Entry<K,V>只提供了一個(gè)構造器 Entry(K key, V value, Entry<K,V> parent)

即:創(chuàng )建一個(gè)紅黑樹(shù)節點(diǎn),只需要指定其存儲的鍵值信息,以及其父節點(diǎn)引用。不需要指定左孩子和右孩子,以及顏色。

成員方法

提供了getKey()方法返回當前節點(diǎn)的key值。

提供了getValue(),setValue(V v)分別用于獲取Value,以及覆蓋Value后返回oldValue

重寫(xiě)了equals()方法用于判斷兩個(gè)紅黑樹(shù)節點(diǎn)是否相同。邏輯是:兩個(gè)紅黑樹(shù)節點(diǎn)的key要么都為null,要么equals結果true,且,value要么都為null,要么equals結果為true。

重寫(xiě)了hashCode()方法。

重寫(xiě)了toString()方法。

五、構造器

public TreeMap()

    public TreeMap() {
        comparator = null;
    }

無(wú)參構造器,即不指定比較器的構造器。

注意,此時(shí)插入集合的鍵值對的key的類(lèi)型必須實(shí)現Comparable接口,即提供自然排序能力,否則會(huì )報錯類(lèi)型轉換異常。 

public TreeMap(Comparator<? super K> comparator)

 public TreeMap(Comparator<? super K> comparator) {
        this.comparator = comparator;
    }

指定比較器的構造器。

指定的比較器用于比較key,且comparator指定了泛型,即比較器比較的元素的類(lèi)型必須是K或者K的父類(lèi)類(lèi)型。

public TreeMap(Map<? extends K, ? extends V> m)

    public TreeMap(Map<? extends K, ? extends V> m) {
        comparator = null;
        putAll(m);
    }

 將非TreeMap集合轉為T(mén)reeMap集合構造器

public TreeMap(SortedMap<K, ? extends V> 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集合轉為T(mén)reeMap集合

六、成員方法

public V get(Object key)

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

TreeMap的get方法用于獲取指定key的value。如果指定key沒(méi)有對應的紅黑樹(shù)節點(diǎn),則返回null,否則返回對應紅黑樹(shù)節點(diǎn)的value。

可以看到get方法實(shí)現依賴(lài)于getEntry(Object key)方法。

getEntry(Object key)方法是根據指定key找對應的紅黑樹(shù)節點(diǎn)并返回該節點(diǎn)。

final Entry<K,V> getEntry(Object key)

    final Entry<K,V> getEntry(Object key) {
        // Offload comparator-based version for sake of performance
        if (comparator != null)//如果外部指定了比較器
            return getEntryUsingComparator(key);//則使用指定比較器來(lái)查找
        if (key == null)//如果外部沒(méi)有指定比較器,且要查找的key為null,則拋出空指針異常
            throw new NullPointerException();
        @SuppressWarnings("unchecked")//此時(shí)外部沒(méi)有指定構造器,且要查的Key不為null
            Comparable<? super K> k = (Comparable<? super K>) key;//檢查Key的類(lèi)型是否實(shí)現了Comparable接口,即是否實(shí)現了自然排序,如果實(shí)現了,則此處可以強轉成功,否則會(huì )報錯類(lèi)型轉換異常
        Entry<K,V> p = root;
        while (p != null) {//從紅黑樹(shù)根節點(diǎn)開(kāi)始使用key本身的自然排序進(jìn)行比較
            int cmp = k.compareTo(p.key);
            if (cmp < 0)//如果要查找的key小于樹(shù)節點(diǎn)的key,則說(shuō)明要找的key在當前節點(diǎn)的左子樹(shù)上,則下次遍歷從左子樹(shù)的根節點(diǎn)開(kāi)始
                p = p.left;
            else if (cmp > 0)//如果要查找的key大于樹(shù)節點(diǎn)的key,則說(shuō)明要找的key在當前節點(diǎn)的右子樹(shù)上,則下次遍歷從右子樹(shù)的根節點(diǎn)開(kāi)始
                p = p.right;
            else//如果要查找的key等于樹(shù)節點(diǎn)的key,則該節點(diǎn)就是要找的,直接返回該節點(diǎn)
                return p;
        }
        return null;//如果上面遍歷沒(méi)有找到對應Key的節點(diǎn),則返回null
    }
 
 
    final Entry<K,V> getEntryUsingComparator(Object key) {//使用指定比較器來(lái)查找,邏輯基本和自然排序查找一樣,只是這里使用了比較器排序查找
        @SuppressWarnings("unchecked")
            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;
    }

 public V put(K key, V value)

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;
    }
final int compare(Object k1, Object k2) {
        return comparator==null ? ((Comparable<? super K>)k1).compareTo((K)k2)
            : comparator.compare((K)k1, (K)k2);
    }
public V setValue(V value) {
            V oldValue = this.value;
            this.value = value;
            return oldValue;
        }

  TreeMap的put方法用于插入一個(gè)鍵值對,

當插入的key在集合中不存在時(shí),則put表示新增鍵值對,并返回null;

當插入的key在集合中存在時(shí),則put表示覆蓋已存在key對應的value,并返回老value。

private void fixAfterInsertion(Entry<K,V> x)

  private void fixAfterInsertion(Entry<K,V> x) {//x是被插入的紅黑樹(shù)節點(diǎn)
        x.color = RED;//默認被插入的節點(diǎn)都是紅色
 
        while (x != null && x != root && x.parent.color == RED) {//如果被插入節點(diǎn)不是根節點(diǎn)
            if (parentOf(x) == leftOf(parentOf(parentOf(x)))) {
                Entry<K,V> y = rightOf(parentOf(parentOf(x)));
                if (colorOf(y) == RED) {
                    setColor(parentOf(x), BLACK);
                    setColor(y, BLACK);
                    setColor(parentOf(parentOf(x)), RED);
                    x = parentOf(parentOf(x));
                } else {
                    if (x == rightOf(parentOf(x))) {
                        x = parentOf(x);
                        rotateLeft(x);
                    }
                    setColor(parentOf(x), BLACK);
                    setColor(parentOf(parentOf(x)), RED);
                    rotateRight(parentOf(parentOf(x)));
                }
            } else {
                Entry<K,V> y = leftOf(parentOf(parentOf(x)));
                if (colorOf(y) == RED) {
                    setColor(parentOf(x), BLACK);
                    setColor(y, BLACK);
                    setColor(parentOf(parentOf(x)), RED);
                    x = parentOf(parentOf(x));
                } else {
                    if (x == leftOf(parentOf(x))) {
                        x = parentOf(x);
                        rotateRight(x);
                    }
                    setColor(parentOf(x), BLACK);
                    setColor(parentOf(parentOf(x)), RED);
                    rotateLeft(parentOf(parentOf(x)));
                }
            }
        }
        root.color = BLACK;//如果被插入的節點(diǎn)是根節點(diǎn),則節點(diǎn)顏色改為黑色
    }

fixAfterInsertion方法用于:當TreeMap插入紅黑樹(shù)節點(diǎn)后,導致紅黑樹(shù)不平衡時(shí),TreeMap保持自平衡的自旋和變色操作。

該方法的入參就是插入的紅黑樹(shù)節點(diǎn)。

到此這篇關(guān)于Java基礎之TreeMap詳解的文章就介紹到這了,更多相關(guān)Java TreeMap詳解內容請搜索腳本之家以前的文章或繼續瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!

免責聲明:本站發(fā)布的內容(圖片、視頻和文字)以原創(chuàng )、來(lái)自本網(wǎng)站內容采集于網(wǎng)絡(luò )互聯(lián)網(wǎng)轉載等其它媒體和分享為主,內容觀(guān)點(diǎn)不代表本網(wǎng)站立場(chǎng),如侵犯了原作者的版權,請告知一經(jīng)查實(shí),將立刻刪除涉嫌侵權內容,聯(lián)系我們QQ:712375056,同時(shí)歡迎投稿傳遞力量。

闺蜜第一次好滑好紧欣欣| 国产精品色内内在线播放| 少妇与黑人一二三区无码| 极品粉嫩嫩模大尺度无码| 饥渴老熟妇乱子伦视频| 欧美丰满熟妇AAAAA片|