一週一源碼之HashMap源碼解析

簡介

HashMap 是一個散列表,它存儲的內容是鍵值對(key-value)映射。其繼承於AbstractMap,實現了Map、Cloneable、java.io.Serializable接口。
實際上,HashMap是個鏈表數組的結構,數組的每一個元素都是hash值相同的鏈表。Java1.8時,HashMap爲鏈表+數組+紅黑樹的數據結構。當每個數組中的鏈表節點超過一個閾值時,這個節點裏的鏈表將會轉換成紅黑樹的結構。

源碼分析

HashMap一共有2300餘行代碼,在這裏不會對諸多的方法一一詳細介紹,只針對核心、常用的代碼分爲幾個部分來解析,以探究ArrayList的實現與特性。

繼承實現關係

HashMap繼承關係

核心成員變量

table

   transient Node<K,V>[] table;

HashMap的鏈表數組,數據都保存在這個數組裏。

其他成員變量

    // 默認初始容量16
    static final int DEFAULT_INITIAL_CAPACITY = 1 << 4; 
    // 最大容量1073741824
    static final int MAXIMUM_CAPACITY = 1 << 30;
    // 默認加載因子
    static final float DEFAULT_LOAD_FACTOR = 0.75f;
    // 一個桶的樹化閾值,當一個桶中的元素個數超過8時,自動轉換成紅黑樹結構
    static final int TREEIFY_THRESHOLD = 8;
    // 一個樹的鏈表還原閾值,當擴容時,一個桶中的元素小於6時,則從紅黑樹還原回鏈表結構
    static final int UNTREEIFY_THRESHOLD = 6;
    // 哈希表的最小樹形化容量,當哈希表中的容量大於這個值時,表中的桶才能進行樹形化,否則桶內元素太多時會擴容,而不是樹形化。 
    // 爲了避免進行擴容、樹形化選擇的衝突,這個值不能小於 4 * TREEIFY_THRESHOLD
    static final int MIN_TREEIFY_CAPACITY = 64;
    transient Set<Map.Entry<K,V>> entrySet;
    // 加載因子
    final float loadFactor;
    transient int modCount;
    // HashMap的大小
    transient int size;
    // 下一次擴容時的閾值,容量*加載因子
    int threshold;

四個構造方法

無參構造方法

將加載因子賦值成默認值。

    public HashMap() {
        this.loadFactor = DEFAULT_LOAD_FACTOR; 
    }

接收初始容量和自定義加載因子

對傳入的值進行合法性校驗,然後使用tableSizeFor方法獲取初始的擴容閾值。

    public HashMap(int initialCapacity, float loadFactor) {
        if (initialCapacity < 0)
            throw new IllegalArgumentException("Illegal initial capacity: " + initialCapacity);
        if (initialCapacity > MAXIMUM_CAPACITY)
            initialCapacity = MAXIMUM_CAPACITY;
        if (loadFactor <= 0 || Float.isNaN(loadFactor))
            throw new IllegalArgumentException("Illegal load factor: " + loadFactor);
        this.loadFactor = loadFactor;
        this.threshold = tableSizeFor(initialCapacity);
    }

接收初始容量

實際上就是調用了上一個構造方法,傳入了默認的加載因子。

    public HashMap(int initialCapacity) {
        this(initialCapacity, DEFAULT_LOAD_FACTOR);
    }

接收一個map

初始化默認加載因子,調用putMapEntries方法填充map

    public HashMap(Map<? extends K, ? extends V> m) {
        this.loadFactor = DEFAULT_LOAD_FACTOR;
        putMapEntries(m, false);
    }

    final void putMapEntries(Map<? extends K, ? extends V> m, boolean evict) {
        int s = m.size();
        if (s > 0) {
            if (table == null) { // pre-size
                // 根據傳入的map的size和當前map的加載因子生成新的加載因子
                float ft = ((float)s / loadFactor) + 1.0F;
                int t = ((ft < (float)MAXIMUM_CAPACITY) ?
                         (int)ft : MAXIMUM_CAPACITY);
                if (t > threshold)
                    threshold = tableSizeFor(t);
            }
            else if (s > threshold)
                // 擴容
                resize();
            // 你看,HashMap的源碼都是用這種方式遍歷的
            for (Map.Entry<? extends K, ? extends V> e : m.entrySet()) {
                K key = e.getKey();
                V value = e.getValue();
                // 循環遍歷每個entryset填充到當前的HashMap
                putVal(hash(key), key, value, false, evict);
            }
        }
    }    

常用私有方法

有幾個很常用的私有方法,會被公有方法調用。在這裏先看看這些私有方法的邏輯。

hash(Object key)

屬於一個很核心的私有方法,計算key的hash值。

    static final int hash(Object key) {
        int h;
        return (key == null) ? 0 : (h = key.hashCode()) ^ (h >>> 16);
    }

這裏我們可以看到,是用這個key的hashCode和經過無符號右移16位後的值做異或運算得到的。

resize()

擴容方法,在put方法中會用到。

    final Node<K,V>[] resize() {
        Node<K,V>[] oldTab = table;
        int oldCap = (oldTab == null) ? 0 : oldTab.length;
        int oldThr = threshold;
        int newCap, newThr = 0;
        if (oldCap > 0) {
            // 原始容量大於0,則校驗是否超過最大值,如果沒有則嘗試容量翻倍,下一次擴容的閾值也翻倍
            if (oldCap >= MAXIMUM_CAPACITY) {
                threshold = Integer.MAX_VALUE;
                return oldTab;
            }
            else if ((newCap = oldCap << 1) < MAXIMUM_CAPACITY &&
                     oldCap >= DEFAULT_INITIAL_CAPACITY)
                newThr = oldThr << 1; // double threshold
        }
        else if (oldThr > 0) // initial capacity was placed in threshold
            newCap = oldThr;
        else {               // zero initial threshold signifies using defaults
            newCap = DEFAULT_INITIAL_CAPACITY;
            newThr = (int)(DEFAULT_LOAD_FACTOR * DEFAULT_INITIAL_CAPACITY);
        }
        if (newThr == 0) {
            float ft = (float)newCap * loadFactor;
            newThr = (newCap < MAXIMUM_CAPACITY && ft < (float)MAXIMUM_CAPACITY ?
                      (int)ft : Integer.MAX_VALUE);
        }
        threshold = newThr;
        @SuppressWarnings({"rawtypes","unchecked"})
            Node<K,V>[] newTab = (Node<K,V>[])new Node[newCap];
        table = newTab;
        // 擴容後填充新的散列
        if (oldTab != null) {
            for (int j = 0; j < oldCap; ++j) {
                Node<K,V> e;
                if ((e = oldTab[j]) != null) {
                    oldTab[j] = null;
                    if (e.next == null)
                        newTab[e.hash & (newCap - 1)] = e;
                    else if (e instanceof TreeNode)
                        ((TreeNode<K,V>)e).split(this, newTab, j, oldCap);
                    else { // preserve order
                        Node<K,V> loHead = null, loTail = null;
                        Node<K,V> hiHead = null, hiTail = null;
                        Node<K,V> next;
                        do {
                            next = e.next;
                            if ((e.hash & oldCap) == 0) {
                                if (loTail == null)
                                    loHead = e;
                                else
                                    loTail.next = e;
                                loTail = e;
                            }
                            else {
                                if (hiTail == null)
                                    hiHead = e;
                                else
                                    hiTail.next = e;
                                hiTail = e;
                            }
                        } while ((e = next) != null);
                        if (loTail != null) {
                            loTail.next = null;
                            newTab[j] = loHead;
                        }
                        if (hiTail != null) {
                            hiTail.next = null;
                            newTab[j + oldCap] = hiHead;
                        }
                    }
                }
            }
        }
        return newTab;
    }

其他核心私有方法

putVal、getNode方法在下面涉及到的地方會進行分析。

添加元素與擴容

putVal

HashMap的put方法有三個:

  • put(K key, V value):最常用的傳入key value
  • putAll(Map < ? extends K, ? extends V> m):傳入一個map
  • putIfAbsent(K key, V value):如果存在key,則不進行value的覆蓋

因爲全部的put操作的核心是putVal方法,在只看putVal方法的實現邏輯。

    /**
     * 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.如果爲false,則按照創建模式執行
     * @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)
            // 如果table爲空,則用resize方法初始化table
            n = (tab = resize()).length;
        if ((p = tab[i = (n - 1) & hash]) == null)
            // 根據hash值找到數組對應的位置,如果當前位置不存在值,則創建新的node將keyvalue存入,否則要加入鏈表的最後位置
            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))))
                // 如果key相同則將當前(鏈表的第一個)節點賦值給e
                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) 
                            // 超過紅黑樹閾值則將鏈表轉爲樹
                            treeifyBin(tab, hash);
                        break;
                    }
                    if (e.hash == hash &&
                        ((k = e.key) == key || (key != null && key.equals(k))))
                        // 如果hash值和key值都相等,則跳出,在下面邏輯將傳入值覆蓋當前節點的值
                        break;
                    p = e;
                }
            }
            if (e != null) { // existing mapping for key
                // 覆蓋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;
    }

通過代碼來簡單總結一下HashMap在存入新節點時都發生了什麼事情。

  • 首先,算出hash值,找到鏈表數組中應該保存的位置,然後看當前位置是否已經有值。
    • 如果爲空,則創建一個新節點保存,結束;
    • 如果有值,則對比當前傳入key與首節點的key值是否相同。
    • 如果相同,則覆蓋當前節點的value
    • 如果不同,則判斷當前節點是否爲樹節點,如果是則調用putTreeVal方法將傳入key value保存到樹節點中
    • 否則,沿着鏈表遍歷。
      • 當發現key值相同的節點,則break,然後在下方邏輯覆蓋value
      • 如果沒有key值相同的節點,則在鏈表末端創建新節點,將傳入的key value保存到新節點

其中,如果數組中鏈表長度大於樹形化閾值,則會調用treeifyBin(Node

final void treeifyBin(Node<K,V>[] tab, int hash) {
        int n, index; Node<K,V> e;
        if (tab == null || (n = tab.length) < MIN_TREEIFY_CAPACITY)
            resize();
        else if ((e = tab[index = (n - 1) & hash]) != null) {
            TreeNode<K,V> hd = null, tl = null;
            do {
                TreeNode<K,V> p = replacementTreeNode(e, null);
                if (tl == null)
                    hd = p;
                else {
                    p.prev = tl;
                    tl.next = p;
                }
                tl = p;
            } while ((e = e.next) != null);
            if ((tab[index] = hd) != null)
                hd.treeify(tab);
        }
    }

取值

get

HashMap的get方法有兩個:

  • get(Object key):獲取key的值
  • getOrDefault(Object key, V defaultValue):獲取key的值,如果不存在則返回傳入的默認defaultValue

兩個get方法的核心都是由getNode方法實現的。

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

實際上與put的核心處理邏輯類似,都是根據key的hash值,去鏈表數組的對應位置取值。如果數組的第一個節點保存的就是傳入的key,則直接返回,否則遍歷鏈表找到對應的值。

containsKey(Object key)

獲取傳入key對應的值,如果不存在則返回false

    public boolean containsKey(Object key) {
        return getNode(hash(key), key) != null;
    }

containsValue(Object value)

判斷是否存在value,這個厲害了,遍歷了整個數組和數組中的每個鏈表。

    public boolean containsValue(Object value) {
        Node<K,V>[] tab; V v;
        if ((tab = table) != null && size > 0) {
            for (int i = 0; i < tab.length; ++i) {
                for (Node<K,V> e = tab[i]; e != null; e = e.next) {
                    if ((v = e.value) == value ||
                        (value != null && value.equals(v)))
                        return true;
                }
            }
        }
        return false;
    }

修改

replace(K key, V value)

找到傳入key值的節點,將其value替換爲傳入的value。如果沒有對應的值則返回null。

    public V replace(K key, V value) {
        Node<K,V> e;
        if ((e = getNode(hash(key), key)) != null) {
            V oldValue = e.value;
            e.value = value;
            afterNodeAccess(e);
            return oldValue;
        }
        return null;
    }

replace(K key, V oldValue, V newValue)

這裏傳入了期望值,也就是說,如果key對應的值是期望值,則用新值覆蓋並返回true,否則不進行覆蓋操作並返回false。

    public boolean replace(K key, V oldValue, V newValue) {
        Node<K,V> e; V v;
        if ((e = getNode(hash(key), key)) != null &&
            ((v = e.value) == oldValue || (v != null && v.equals(oldValue)))) {
            e.value = newValue;
            afterNodeAccess(e);
            return true;
        }
        return false;
    }

移除元素

remove

remove方法有三個:

  • remove(Object key):移除傳入key對應的節點
  • remove(Object key, Object value):如果key對應的value是傳入的期望value,則移除

二者的核心方法都是removeNode方法

    final Node<K,V> removeNode(int hash, Object key, Object value,
                               boolean matchValue, boolean movable) {
        Node<K,V>[] tab; Node<K,V> p; int n, index;
        if ((tab = table) != null && (n = tab.length) > 0 &&
            (p = tab[index = (n - 1) & hash]) != null) {
            Node<K,V> node = null, e; K k; V v;
            if (p.hash == hash &&
                ((k = p.key) == key || (key != null && key.equals(k))))
                node = p;
            else if ((e = p.next) != null) {
                if (p instanceof TreeNode)
                    node = ((TreeNode<K,V>)p).getTreeNode(hash, key);
                else {
                    do {
                        if (e.hash == hash &&
                            ((k = e.key) == key ||
                             (key != null && key.equals(k)))) {
                            node = e;
                            break;
                        }
                        p = e;
                    } while ((e = e.next) != null);
                }
            }
            if (node != null && (!matchValue || (v = node.value) == value ||
                                 (value != null && value.equals(v)))) {
                if (node instanceof TreeNode)
                    ((TreeNode<K,V>)node).removeTreeNode(this, tab, movable);
                else if (node == p)
                    tab[index] = node.next;
                else
                    p.next = node.next;
                ++modCount;
                --size;
                afterNodeRemoval(node);
                return node;
            }
        }
        return null;
    }

其實也是和put與get的核心邏輯類似,都是找到對應的節點。這裏將節點從鏈表中刪去。

clear()

將size置爲0並遍歷table將每一個元素置爲空。

    public void clear() {
        Node<K,V>[] tab;
        modCount++;
        if ((tab = table) != null && size > 0) {
            size = 0;
            for (int i = 0; i < tab.length; ++i)
                tab[i] = null;
        }
    }

其他方法

entrySet()

返回entrySet,一個泛型爲Map.Entry

內部類

Node

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

EntrySet

在調用entrySet()方法的時候,如果entrySet爲null,則返回一個EntrySet對象。

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

KeySet和Values與此類似。

最後

todo

在讀代碼的時候,有一個點一直搞不懂,就是entrySet是怎麼維護的。因爲源碼中沒有見到在put時有對entrySet處理的過程,但是當新增節點之後,entrySet裏面就已經存在這個節點了,一直讓我不是很理解。之後需要研究一下這裏是怎麼實現的。還有一點,就是對於紅黑樹的原理並不是很瞭解,因此這也是下一步需要研究的。

參考資料

深入分析hashmap
二進制的位運算

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