jdk源碼之java集合類(四)——Map & Set

我們來看一下Map和Set這兩個集合

前兩篇我們已經把List和Queue給看完了,這一篇之所以Map和Set一起看,主要是由於Map和Set的關係太緊密了。雖然在接口定義的時候二者並沒有太緊密的聯繫,無非就是Map會返回關於Key的Set、Value的List以及Key-Value組合的Map.Entry的Set。但是,在二者實現類在實現的時候,尤其是Set在實現的時候,幾乎就是把Map給用了一遍。所以如果單純講Set的話,我們除了看一看Set的類族結構外,其餘的都會由一句“它調用了對應的Map,我們留到Map章節再講”來結束,所以,爲了讓閱讀更加直接徹底,我們將Map和Set放在一章中完成講解。

Map和Set擁有不少實現類,爲了方便起見,我們以其中最具代表性的Hash和Tree爲主要實現類來講解,先看類圖:

可以看到,Set和Map在類族設計上是完全對應的,Set有AbstractSet,Map有AbstractMap。而對應又有HashSet、TreeSet,而HashSet和TreeSet又分別和HashMap和TreeMap聚合。

一、接口設計

我們先看Set的接口設計,直接上圖:

在Set的接口中,最重要的應該屬於add和contains方法了,Set和List的區別在於,它不順序地存儲數據,而是以一定規律存放,因此它不具有按index獲取(get方法)的功能,但是卻方便了contains(檢查是否存在)方法的作用。

然後再看Map:

Map中除了基本的增刪改查(put、remove、get等等)外,最具特性的遍歷性質方法有三:entrySet、keySet、values,分別返回key-value鍵值對的Set、key的Set、value的list

值得一提的自然是這個鍵值對,在Map接口中還有個內部接口Map.Entry:

這個接口的作用主要存放鍵值對,事實上這個接口還是非常重要的,我們接下來看實現的時候便知道了。

二、抽象類

先來看AbstractSet,AbstractSet在繼承了AbstractCollection以後只實現了三個方法:equals、hashCode、removeAll。前兩個方法我們單純從集合的角度看似乎不怎麼要緊,而removeAll無非也是調用了迭代器的remove方法:

    public boolean removeAll(Collection<?> c) {
        Objects.requireNonNull(c);
        boolean modified = false;

        if (size() > c.size()) {
            for (Iterator<?> i = c.iterator(); i.hasNext(); )
                modified |= remove(i.next());
        } else {
            for (Iterator<?> i = iterator(); i.hasNext(); ) {
                if (c.contains(i.next())) {
                    i.remove();
                    modified = true;
                }
            }
        }
        return modified;
    }

通常根據我們的經驗,迭代器的實現(在子類中實現)無非也是調用子類本身具有的增刪方法。

然後再看AbstractMap,相比起AbstractSet,AbstractMap這個抽象類就顯得非常“勞心”了,他替子類完成了一系列重要的方法,我們簡單看幾個:

    public boolean containsValue(Object value) {
        Iterator<Entry<K,V>> i = entrySet().iterator();
        if (value==null) {
            while (i.hasNext()) {
                Entry<K,V> e = i.next();
                if (e.getValue()==null)
                    return true;
            }
        } else {
            while (i.hasNext()) {
                Entry<K,V> e = i.next();
                if (value.equals(e.getValue()))
                    return true;
            }
        }
        return false;
    }

containsValue,用來檢測是否包含此類value值,通過獲取entrySet的迭代器(說白了就是遍歷entrySet)然後檢查是否有哪個value和傳入值一樣。與這個方法類似的還有containsKey,這裏就不展示源碼了;

    public V get(Object key) {
        Iterator<Entry<K,V>> i = entrySet().iterator();
        if (key==null) {
            while (i.hasNext()) {
                Entry<K,V> e = i.next();
                if (e.getKey()==null)
                    return e.getValue();
            }
        } else {
            while (i.hasNext()) {
                Entry<K,V> e = i.next();
                if (key.equals(e.getKey()))
                    return e.getValue();
            }
        }
        return null;
    }

get方法,如此核心的方法被放在抽象類中實現,這在幾大集合家族中是絕無僅有的(別的較少參數的get調用較多參數的get的不算),究其原因還是在Map中,get方法可以不直接和數據源的存儲方式相關,它獲取entrySet,並通過遍歷的方式拿到需要的值。

但是,對的我要說但是了,這樣的get方法顯然在效率上很有問題,所以事實上這裏的get方法只是給了Map家族一個最基本(也可以說最差的)get的實現,事實上在其子類中都會重寫get方法。此外remove和get也類似,遍歷entrySet。

    public void putAll(Map<? extends K, ? extends V> m) {
        for (Map.Entry<? extends K, ? extends V> e : m.entrySet())
            put(e.getKey(), e.getValue());
    }

putAll,調用尚未被實現的put方法完成該完成的事情。

AbstractMap中幾乎提供了put以外所以方法的基本實現,但是其在子類中均被重寫,與get方法相同,AbstractMap中許多方法都是給出了最基本的實現方式,以便讓一些並沒有更優實現方式的數據結構不用去重複實現。但是由於我們本文主要閱讀的是Hash和Tree,這種實現顯然並沒有太大效應,所以我們可以直接略過去閱讀子類的實現。

三、HashSet & HashMap

先看HashSet吧,HashSet中:

    private transient HashMap<E,Object> map;

    // Dummy value to associate with an Object in the backing Map
    private static final Object PRESENT = new Object();

    /**
     * Constructs a new, empty set; the backing <tt>HashMap</tt> instance has
     * default initial capacity (16) and load factor (0.75).
     */
    public HashSet() {
        map = new HashMap<>();
    }

包含了一個HashMap,並在構造函數中初始化。

    public Iterator<E> iterator() {
        return map.keySet().iterator();
    }

    public int size() {
        return map.size();
    }

    public boolean isEmpty() {
        return map.isEmpty();
    }

    public boolean add(E e) {
        return map.put(e, PRESENT)==null;
    }
。。。。。。。

之後的所有方法都是調用HashMap來完成的。。。。(這可能是我看到現在最水的一個實現類了唉哈哈哈)

那麼既然如此,就直接來看HashMap吧,事實上在前面的文章jdk源碼之java集合類(一)中我已簡單講解了HashMap的實現以及HashMap和HashTable的區別,並給出了最基本的add方法的源碼解讀。這裏權且作爲複習再詳細看一遍:

    static class Node<K,V> implements Map.Entry<K,V> {
        final int hash;
        final K key;
        V value;
        Node<K,V> next;

        Node(int hash, K key, V value, Node<K,V> next) {
            this.hash = hash;
            this.key = key;
            this.value = value;
            this.next = next;
        }

        public final K getKey()        { return key; }
        public final V getValue()      { return value; }
        public final String toString() { return key + "=" + value; }

        public final int hashCode() {
            return Objects.hashCode(key) ^ Objects.hashCode(value);
        }

        public final V setValue(V newValue) {
            V oldValue = value;
            value = newValue;
            return oldValue;
        }

        public final boolean equals(Object o) {
            if (o == this)
                return true;
            if (o instanceof Map.Entry) {
                Map.Entry<?,?> e = (Map.Entry<?,?>)o;
                if (Objects.equals(key, e.getKey()) &&
                    Objects.equals(value, e.getValue()))
                    return true;
            }
            return false;
        }
    }

首先他給出鍵值對的存放單元Map.Entry的實現類Node。這個實現沒啥好說的,應該都看得懂。

    /**
     * The table, initialized on first use, and resized as
     * necessary. When allocated, length is always a power of two.
     * (We also tolerate length zero in some operations to allow
     * bootstrapping mechanics that are currently not needed.)
     */
    transient Node<K,V>[] table;

而後hashMap內部存放一個Node的數組。

    /**
     * Holds cached entrySet(). Note that AbstractMap fields are used
     * for keySet() and values().
     */
    transient Set<Map.Entry<K,V>> entrySet;

    /**
     * The number of key-value mappings contained in this map.
     */
    transient int size;

並且記錄長度。

    public V get(Object key) {
        Node<K,V> e;
        return (e = getNode(hash(key), key)) == null ? null : e.value;
    }

    /**
     * Implements Map.get and related methods
     *
     * @param hash hash for key
     * @param key the key
     * @return the node, or null if none
     */
    final Node<K,V> getNode(int hash, Object key) {
        Node<K,V>[] tab; Node<K,V> first, e; int n; K k;
        if ((tab = table) != null && (n = tab.length) > 0 &&
            (first = tab[(n - 1) & hash]) != null) {
            if (first.hash == hash && // always check first node
                ((k = first.key) == key || (key != null && key.equals(k))))
                return first;
            if ((e = first.next) != null) {
                if (first instanceof TreeNode)
                    return ((TreeNode<K,V>)first).getTreeNode(hash, key);
                do {
                    if (e.hash == hash &&
                        ((k = e.key) == key || (key != null && key.equals(k))))
                        return e;
                } while ((e = e.next) != null);
            }
        }
        return null;
    }

重寫抽象類中遍歷獲取的get方法,通過hash值和表長度求並運算的結果來得到位置的下標,返回其值。

    public V put(K key, V value) {
        return putVal(hash(key), key, value, false, true);
    }

    /**
     * Implements Map.put and related methods
     *
     * @param hash hash for key
     * @param key the key
     * @param value the value to put
     * @param onlyIfAbsent if true, don't change existing value
     * @param evict if false, the table is in creation mode.
     * @return previous value, or null if none
     */
    final V putVal(int hash, K key, V value, boolean onlyIfAbsent,
                   boolean evict) {
        Node<K,V>[] tab; Node<K,V> p; int n, i;
        if ((tab = table) == null || (n = tab.length) == 0)
            n = (tab = resize()).length;
        if ((p = tab[i = (n - 1) & hash]) == null)
            tab[i] = newNode(hash, key, value, null);
        else {
            Node<K,V> e; K k;
            if (p.hash == hash &&
                ((k = p.key) == key || (key != null && key.equals(k))))
                e = p;
            else if (p instanceof TreeNode)
                e = ((TreeNode<K,V>)p).putTreeVal(this, tab, hash, key, value);
            else {
                for (int binCount = 0; ; ++binCount) {
                    if ((e = p.next) == null) {
                        p.next = newNode(hash, key, value, null);
                        if (binCount >= TREEIFY_THRESHOLD - 1) // -1 for 1st
                            treeifyBin(tab, hash);
                        break;
                    }
                    if (e.hash == hash &&
                        ((k = e.key) == key || (key != null && key.equals(k))))
                        break;
                    p = e;
                }
            }
            if (e != null) { // existing mapping for key
                V oldValue = e.value;
                if (!onlyIfAbsent || oldValue == null)
                    e.value = value;
                afterNodeAccess(e);
                return oldValue;
            }
        }
        ++modCount;
        if (++size > threshold)
            resize();
        afterNodeInsertion(evict);
        return null;
    }

put方法相對複雜一些,他需要先判斷hash&length位置是否爲空,若是,則直接複製,若非,即如果當前key已經在表裏,則覆蓋value的值。並且還會返回oldValue的值。但是如果這個位置的值還是不對,即hash&length這個位置被佔了,但是佔位的爲null或者佔位的key不等於傳入的key,就往後移動下標直到找到。(典型hash表的處理),如果還是找不到,size大於這個threshold,就重新調整數組的大小。

這裏順便也可以理解爲何size不直接用數組的length來表達(好像這是個很蠢的問題)

增和查都看了,刪除修改應該也差不多,我們把核心往遍歷上靠。去看一看幾個Set的方法:

    public Set<K> keySet() {
        Set<K> ks;
        return (ks = keySet) == null ? (keySet = new KeySet()) : ks;
    }

    final class KeySet extends AbstractSet<K> {
        public final int size()                 { return size; }
        public final void clear()               { HashMap.this.clear(); }
        public final Iterator<K> iterator()     { return new KeyIterator(); }
        public final boolean contains(Object o) { return containsKey(o); }
        public final boolean remove(Object key) {
            return removeNode(hash(key), key, null, false, true) != null;
        }
        public final Spliterator<K> spliterator() {
            return new KeySpliterator<>(HashMap.this, 0, -1, 0, 0);
        }
        public final void forEach(Consumer<? super K> action) {
            Node<K,V>[] tab;
            if (action == null)
                throw new NullPointerException();
            if (size > 0 && (tab = table) != null) {
                int mc = modCount;
                for (int i = 0; i < tab.length; ++i) {
                    for (Node<K,V> e = tab[i]; e != null; e = e.next)
                        action.accept(e.key);
                }
                if (modCount != mc)
                    throw new ConcurrentModificationException();
            }
        }
    }

keySet,我一直感覺這個設計非常騷:HashSet裏有HashMap,HashMap又有KeySet。。。

話說我們看到KeySet,總體來講很好理解,但是有一點不太明白,就是幾個基本操作:add、remove等等沒有實現,因爲其父類是AbstractSet,我們剛剛前面也說了AbstractSet基本啥也沒幹。這裏我們要看到AbstractCollection裏的實現:

    public boolean add(E e) {
        throw new UnsupportedOperationException();
    }

在講解List家族的時候我曾經說過,AbstractCollection具有典型的抽象類設計特點,把最核心的部分留給子類實現。但是我當時並沒有提到爲何這裏要通過直接拋異常的方式實現add,而不是將其作爲抽象方法強制子類去實現?

我曾經在一篇學習總結中對反射有個定義:拋棄編譯檢查,把錯誤留給Exception;誠然這種方式確實降低了容錯性,但是如果開發人員有做過詳細的單元測試的話,這種容錯上的問題基本可以忽略,替代它的則是更靈活的實現方式。

集合,作爲一種工具類,他不需要開發人員批量去實現,相反的只需要根據也無需要去調用所需的集合,或是自己實現一兩個自己需要的集合即可,作爲工具類,完整的單元測試的需要是不可避免的。而AbstractCollection中這種設計給與那些不願提供對應操作的集合類的實現提供了方便。譬如這裏的keySet,我們幾乎可以肯定,HashMap的keySet勢必是隻讀的,其寫操作應該在HashMap中完成。而也是由於AbstractCollection將對應操作實現成爲直接拋出異常而不是留作抽象方法,因此keySet可以免去這個勢必會拋出異常的方法的實現步驟。

    public Collection<V> values() {
        Collection<V> vs;
        return (vs = values) == null ? (values = new Values()) : vs;
    }

    final class Values extends AbstractCollection<V> {
        public final int size()                 { return size; }
        public final void clear()               { HashMap.this.clear(); }
        public final Iterator<V> iterator()     { return new ValueIterator(); }
        public final boolean contains(Object o) { return containsValue(o); }
        public final Spliterator<V> spliterator() {
            return new ValueSpliterator<>(HashMap.this, 0, -1, 0, 0);
        }
        public final void forEach(Consumer<? super V> action) {
            Node<K,V>[] tab;
            if (action == null)
                throw new NullPointerException();
            if (size > 0 && (tab = table) != null) {
                int mc = modCount;
                for (int i = 0; i < tab.length; ++i) {
                    for (Node<K,V> e = tab[i]; e != null; e = e.next)
                        action.accept(e.value);
                }
                if (modCount != mc)
                    throw new ConcurrentModificationException();
            }
        }
    }

    /**
     * Returns a {@link Set} view of the mappings contained in this map.
     * The set is backed by the map, so changes to the map are
     * reflected in the set, and vice-versa.  If the map is modified
     * while an iteration over the set is in progress (except through
     * the iterator's own <tt>remove</tt> operation, or through the
     * <tt>setValue</tt> operation on a map entry returned by the
     * iterator) the results of the iteration are undefined.  The set
     * supports element removal, which removes the corresponding
     * mapping from the map, via the <tt>Iterator.remove</tt>,
     * <tt>Set.remove</tt>, <tt>removeAll</tt>, <tt>retainAll</tt> and
     * <tt>clear</tt> operations.  It does not support the
     * <tt>add</tt> or <tt>addAll</tt> operations.
     *
     * @return a set view of the mappings contained in this map
     */
    public Set<Map.Entry<K,V>> entrySet() {
        Set<Map.Entry<K,V>> es;
        return (es = entrySet) == null ? (entrySet = new EntrySet()) : es;
    }

    final class EntrySet extends AbstractSet<Map.Entry<K,V>> {
        public final int size()                 { return size; }
        public final void clear()               { HashMap.this.clear(); }
        public final Iterator<Map.Entry<K,V>> iterator() {
            return new EntryIterator();
        }
        public final boolean contains(Object o) {
            if (!(o instanceof Map.Entry))
                return false;
            Map.Entry<?,?> e = (Map.Entry<?,?>) o;
            Object key = e.getKey();
            Node<K,V> candidate = getNode(hash(key), key);
            return candidate != null && candidate.equals(e);
        }
        public final boolean remove(Object o) {
            if (o instanceof Map.Entry) {
                Map.Entry<?,?> e = (Map.Entry<?,?>) o;
                Object key = e.getKey();
                Object value = e.getValue();
                return removeNode(hash(key), key, value, true, true) != null;
            }
            return false;
        }
        public final Spliterator<Map.Entry<K,V>> spliterator() {
            return new EntrySpliterator<>(HashMap.this, 0, -1, 0, 0);
        }
        public final void forEach(Consumer<? super Map.Entry<K,V>> action) {
            Node<K,V>[] tab;
            if (action == null)
                throw new NullPointerException();
            if (size > 0 && (tab = table) != null) {
                int mc = modCount;
                for (int i = 0; i < tab.length; ++i) {
                    for (Node<K,V> e = tab[i]; e != null; e = e.next)
                        action.accept(e);
                }
                if (modCount != mc)
                    throw new ConcurrentModificationException();
            }
        }
    }

其values和entrySet方法的實現細節也類似,這裏就不做詳解了。

四、TreeMap

TreeSet的實現和HashSet類似,基本是調用TreeMap來實現的,我們就直接看TreeMap的實現吧。

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

先來看他特別標準的樹節點Entry的實現,key、value,左節點右節點。

    private transient Entry<K,V> root;

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

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

存放根節點。

至於其內部的具體實現,其實基本就是樹結構的一個java實現而已,我們這裏可以看個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;
        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;
    }

step1:看看樹是否爲空,若是,把根節點設置爲新傳入的key-value;

step2:從根節點開始遍歷,比較節點的key和傳入的key,若大,往右,若小,往左,若爲空,則賦值。

這裏還有個細節就是comparator是否存在,TreeMap是允許傳入比較器的,如果有比較器就通過比較器比較,如果沒有則根據默認的比較方法(這裏這個默認比較方法比較複雜,就是key的類型必須實現Comparable接口,基本上麼。。。看圖)

可以看到我們通常認爲能比較的東西都可以比較,不能比較的東西你要麼自己去實現比較的方式,要麼就讓這個被比較的東西自己實現可比較(comparable)接口。

看完put方法以後,對於TreeMap的內部數據結構應該有個大概瞭解了,其餘的方法就不再敘述了,有興趣自行閱讀源碼。

小結

到目前爲止,我們已經把List、Queue、Set、Map的基本情況都說明了,本篇雖然略過了HashTable、ConcurrentHashMap之類的方法,但是一來是因爲集合類的第一篇已經描述過了,二來是後面我再重新閱讀CAS的時候或許還會重新提到Concurrent的一些集合類。

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