1. 程式人生 > >【Java8原始碼分析】集合框架-HashMap

【Java8原始碼分析】集合框架-HashMap

一、HashMap的儲存結構

總共有兩種儲存類

// 1. 雜湊衝突時採用連結串列法的類,一個雜湊桶多於8個元素改為TreeNode
static class Node<K,V> implements Map.Entry<K,V>
// 2. 雜湊衝突時採用紅黑樹儲存的類,一個雜湊桶少於6個元素改為Node
static final class TreeNode<K,V> extends LinkedHashMap.Entry<K,V>

下面詳細看一下Node類

   // 每個雜湊桶的儲存結構,重寫了equals和hashCode
    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; } }

二、hash值計算和hash桶對映

下面為hash值計算方法,至於這個演算法為什麼高效和均勻,有待研究

    // hash演算法,演算法比較高效、均勻
    static final int hash(Object key) {
        int h;
        return (key == null) ? 0 : (h = key.hashCode()) ^ (h >>> 16);
    }

由hash值對映hash桶的標號

// n為hash桶的個數,比較好理解
(n - 1) & hash

三、原始碼分析

package java.util;

import java.io.IOException;
import java.io.InvalidObjectException;
import java.io.Serializable;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.util.function.BiConsumer;
import java.util.function.BiFunction;
import java.util.function.Consumer;
import java.util.function.Function;

public class HashMap<K,V> extends AbstractMap<K,V>
    implements Map<K,V>, Cloneable, Serializable {

    private static final long serialVersionUID = 362498820763181265L;

    // 預設容器初始大小為16
    static final int DEFAULT_INITIAL_CAPACITY = 1 << 4;

    static final int MAXIMUM_CAPACITY = 1 << 30;

    // 預設裝載因子0.75
    static final float DEFAULT_LOAD_FACTOR = 0.75f;

    // 在解決雜湊衝突時,超過8個元素,採用紅黑樹替換連結串列
    static final int TREEIFY_THRESHOLD = 8;

    // 在解決雜湊衝突時,低於6個元素,將紅黑書轉為連結串列
    static final int UNTREEIFY_THRESHOLD = 6;

    // 採用紅黑樹替換連結串列時,要求容器容量最小為64,否則採用擴容方式
    static final int MIN_TREEIFY_CAPACITY = 64;

    // hash演算法,演算法比較高效、均勻
    static final int hash(Object key) {
        int h;
        return (key == null) ? 0 : (h = key.hashCode()) ^ (h >>> 16);
    }

    // 返回不小於cap的2的次方的數
    static final int tableSizeFor(int cap) {
        int n = cap - 1;
        n |= n >>> 1;
        n |= n >>> 2;
        n |= n >>> 4;
        n |= n >>> 8;
        n |= n >>> 16;
        return (n < 0) ? 1 : (n >= MAXIMUM_CAPACITY) ? MAXIMUM_CAPACITY : n + 1;
    }

    /* ---------------- Fields -------------- */

    // 所有的雜湊桶
    transient Node<K,V>[] table;

    // 用作快取
    transient Set<Map.Entry<K,V>> entrySet;

    transient int size;

    // 這個在ArrayList和LinkedList裡已經見過,用來實現fast-fail
    transient int modCount;

    // HashMap的閾值,用於判斷是否需要調整HashMap的容量(threshold = 容量*裝載因子) 
    int threshold;

    // 裝載因子
    final float loadFactor;

    // 構造方法,對於能預估容量大小的,可以指定一個初始容量,減少擴容操作
    // 裝載因子一般採用預設的0.75即可
    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;
        // 不小於容量的2的次方數
        this.threshold = tableSizeFor(initialCapacity);
    }

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

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

    // 該構造方法先初始化一個空的hashmap,再把所有元素新增進去
    public HashMap(Map<? extends K, ? extends V> m) {
        this.loadFactor = DEFAULT_LOAD_FACTOR;
        // 把一個Map全部新增入HashMap
        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
                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();
            for (Map.Entry<? extends K, ? extends V> e : m.entrySet()) {
                K key = e.getKey();
                V value = e.getValue();
                putVal(hash(key), key, value, false, evict);
            }
        }
    }

    public int size() {
        return size;
    }

    public boolean isEmpty() {
        return size == 0;
    }

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

    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 &&
            // 注意這裡的 (n-1) & hash 為根據hash值計算出hash桶
            (first = tab[(n - 1) & hash]) != null) {
            // 檢查第一個節點,對於沒有hash衝突的桶,第一個元素即為查詢元素
            if (first.hash == hash &&
                ((k = first.key) == key || (key != null && key.equals(k))))
                return first;
            if ((e = first.next) != null) {
                // 如果hash桶已經樹化,即超過8個元素轉為紅黑樹
                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;
    }

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

    // 新增元素
    public V put(K key, V value) {
        return putVal(hash(key), key, value, false, true);
    }

    // onlyIfAbsent如果為true,只有在hashmap沒有該key的時候才新增
    // evict如果為false,hashmap為建立模式
    // 這兩個引數均為實現java8的新介面而設定
    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)
            // 如果hash桶為空,直接插入
            tab[i] = newNode(hash, key, value, null);
        else {
            // 此處e為key值跟要插入元素相等的元素
            // 下面程式碼為找出e
            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;
    }

    // 擴容函式,如果hash桶為空,初始化預設大小,否則雙倍擴容
    // 注意!!因為擴容為2的倍數,根據hash桶的計算方法,元素雜湊值不變
    // 所以元素在新的hash桶的下標,要不跟舊的hash桶下標一致,要不增加1倍
    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) {
            if (oldCap >= MAXIMUM_CAPACITY) {
                threshold = Integer.MAX_VALUE;
                return oldTab;
            }
            else if ((newCap = oldCap << 1) < MAXIMUM_CAPACITY &&
                     oldCap >= DEFAULT_INITIAL_CAPACITY)
                // 雙倍擴容
                newThr = oldThr << 1;
        }
        else if (oldThr > 0)
            newCap = oldThr;
        else { 
            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;

        // 新建擴容後的hash桶,需要把舊桶裡的元素搬到新桶下去
        // 需根據元素的hash值重新計算新桶中的位置
        @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;
    }

    // 把連結串列轉為紅黑樹
    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);
        }
    }
}

四、總結說明

  • HashMap預設的初始容量為16,裝載因子為0.75
  • Hash衝突中連結串列結構的數量大於8個,則呼叫樹化轉為紅黑樹結構,紅黑樹查詢稍微快些;紅黑樹結構的數量小於6個時,則轉為連結串列結構
  • 如果載入因子越大,對空間的利用更充分,但是查詢效率會降低(連結串列長度會越來越長);如果載入因子太小,那麼表中的資料將過於稀疏(很多空間還沒用,就開始擴容了),對空間造成嚴重浪費。如果我們在構造方法中不指定,則系統預設載入因子為0.75,這是一個比較理想的值,一般情況下我們是無需修改的。
  • 一般對雜湊表的雜湊很自然地會想到用hash值對length取模(即除法雜湊法),Hashtable中也是這樣實現的,這種方法基本能保證元素在雜湊表中雜湊的比較均勻,但取模會用到除法運算,效率很低,HashMap中則通過h&(length-1)的方法來代替取模,同樣實現了均勻的雜湊,但效率要高很多,這也是HashMap對Hashtable的一個改進。
  • 雜湊表的容量一定要是2的整數次冪。首先,length為2的整數次冪的話,h&(length-1)就相當於對length取模,這樣便保證了雜湊的均勻,同時也提升了效率;其次,length為2的整數次冪的話,為偶數,這樣length-1為奇數,奇數的最後一位是1,這樣便保證了h&(length-1)的最後一位可能為0,也可能為1(這取決於h的值),即與後的結果可能為偶數,也可能為奇數,這樣便可以保證雜湊的均勻性,而如果length為奇數的話,很明顯length-1為偶數,它的最後一位是0,這樣h&(length-1)的最後一位肯定為0,即只能為偶數,這樣任何hash值都只會被雜湊到陣列的偶數下標位置上,這便浪費了近一半的空間,因此,length取2的整數次冪,是為了使不同hash值發生碰撞的概率較小,這樣就能使元素在雜湊表中均勻地雜湊。

五、參考