Java——HashMap源碼解析

如下針對JDK 1.8版本中的HashMap進行分析。html

概述

    哈希表基於Map接口的實現。此實現提供了全部可選的映射操做,而且容許鍵爲null,值也爲null。HashMap 除了不支持同步操做以及支持null的鍵值外,其功能大體等同於 Hashtable。這個類不保證元素的順序,而且也不保證隨着時間的推移,元素的順序不會改變。java

    假設散列函數使得元素在哈希桶中分佈均勻,那麼這個實現對於 putget 等操做提供了常數時間的性能。node

    對於一個 HashMap 的實例,有兩個因子影響着其性能:初始容量負載因子。容量就是哈希表中哈希桶的個數,初始容量就是哈希表被初次建立時的容量大小。負載因子是在進行自動擴容以前衡量哈希表存儲鍵值對的一個指標。當哈希表中的鍵值對超過capacity * loadfactor時,就會進行 resize 的操做。數組

    做爲通常規則,默認負載因子(0.75)在時間和空間成本之間提供了良好的折衷。負載因子越大,空間開銷越小,可是查找的開銷變大了。併發

    注意,迭代器的快速失敗行爲不能獲得保證,通常來講,存在非同步的併發修改時,不可能做出任何堅定的保證。快速失敗迭代器盡最大努力拋出ConcurrentModificationException異常。所以,編寫依賴於此異常的程序的作法是錯誤的,正確作法是:迭代器的快速失敗行爲應該僅用於檢測程序錯誤。app

源碼分析

主要字段

/**
 * 初始容量大小 —— 必須是2的冪次方
 */
static final int DEFAULT_INITIAL_CAPACITY = 1 << 4; // aka 16

/**
 * 最大容量
 */
static final int MAXIMUM_CAPACITY = 1 << 30;

/**
 * 默認負載因子
 */
static final float DEFAULT_LOAD_FACTOR = 0.75f;

/**
 * 當鏈表長度超過這個值時轉換爲紅黑樹
 */
static final int TREEIFY_THRESHOLD = 8;

/**
 * 樹形閾值,當小於這個值時,紅黑樹轉換爲鏈表
 */
static final int UNTREEIFY_THRESHOLD = 6;

/**
 * The smallest table capacity for which bins may be treeified.
 * (Otherwise the table is resized if too many nodes in a bin.)
 * Should be at least 4 * TREEIFY_THRESHOLD to avoid conflicts
 * between resizing and treeification thresholds.
 */
static final int MIN_TREEIFY_CAPACITY = 64;


/**
 * table 在第一次使用時進行初始化並在須要的時候從新調整自身大小。對於 table 的大小必須是2的冪次方。
 */
transient Node<K,V>[] table;

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

/**
 * 鍵值對的個數
 */
transient int size;

/**
 * HashMap 進行結構性調整的次數。結構性調整指的是增長或者刪除鍵值對等操做,注意對於更新某個鍵的值不是結構特性調整。
 */
transient int modCount;

/**
 * 所能容納的 key-value 對的極限(表的大小 capacity * load factor),達到這個容量時進行擴容操做。
 */
int threshold;

/**
 * 負載因子,默認值爲 0.75
 */
final float loadFactor;

    從上面咱們能夠得知,HashMap中指定的哈希桶數組<u>table.length</u>必須是2的冪次方,這與常規性的把哈希桶數組設計爲素數不同。指定爲2的冪次方主要是在兩方面作優化:函數

  • 擴容:擴容的時候,哈希桶擴大爲當前的兩倍,所以只須要進行左移操做
  • 取模:因爲哈希桶的個數爲2的冪次,所以能夠用**&**操做來替代耗時的模運算, n % table.length -> n & (table.length - 1)

哈希函數

/**
 * 哈希函數
 */
static final int hash(Object key) {
    int h;
    return (key == null) ? 0 : (h = key.hashCode()) ^ (h >>> 16);
}

    key 的哈希值經過它自身hashCode的高十六位與低十六位進行亦或獲得。這麼作得緣由是由於,因爲哈希表的大小固定爲 2 的冪次方,那麼某個 key 的 hashCode 值大於 table.length,其高位就不會參與到 hash 的計算(對於某個 key 其所在的桶的位置的計算爲 hash & (table.length - 1))。所以經過hashCode()的高16位異或低16位實現的:(h = key.hashCode()) ^ (h >>> 16),主要是從速度、功效、質量來考慮的,保證了高位 Bits 也能參與到 Hash 的計算。源碼分析

tableSizeFor函數

/**
 * 返回大於等於capacity的最小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;
}

    根據註釋能夠知道,這個函數返回大於或等於cap的最小二的整數次冪的值。好比對於3,返回4;對於10,返回16。詳解以下: 假設對於n(32位數)其二進制爲 01xx...xx, n >>> 1,進行無符號右移一位, 001xx..xx,位或得 011xx..xx n >>> 2,進行無符號右移兩位, 00011xx..xx,位或得 01111xx..xx 依此類推,無符號右移四位再進行位或將獲得8個1,無符號右移八位再進行位或將獲得16個1,無符號右移十六位再進行位或將獲得32個1。根據這個咱們能夠知道進行這麼屢次無符號右移及位或操做,那麼可以讓數n的二進制位最高位爲1的後面的二進制位所有變成1。此時進行 +1 操做,便可獲得最小二的整數次冪的值。(《高效程序的奧祕》第3章——2的冪界方 有對此進行進一步討論,可自行查看) 回到上面的程序,之因此在開頭先進行一次 -1 操做,是爲了防止傳入的cap自己就是二的冪次方,此時獲得的就是下一個二的冪次方了,好比傳入4,那麼在不進行 -1 的狀況下,將獲得8。性能

構造函數

/**
 * 傳入指定的初始容量和負載因子
 */
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);
}

    對於上面的構造器,咱們須要注意的是this.threshold = tableSizeFor(initialCapacity);這邊的 threshold 爲 2的冪次方,而不是capacity * load factor,固然此處並不是是錯誤,由於此時 table 並無真正的被初始化,初始化動做被延遲到了putVal()當中,因此 threshold 會被從新計算。優化

/**
 * 根據指定的容量以及默認負載因子(0.75)初始化一個空的 HashMap 實例
 *
 * 若是 initCapacity是負數,那麼將拋出 IllegalArgumentException
 */
public HashMap(int initialCapacity) {
    this(initialCapacity, DEFAULT_LOAD_FACTOR);
}

/**
 * 根據默認的容量和負載因子初始化一個空的 HashMap 實例
 */
public HashMap() {
    this.loadFactor = DEFAULT_LOAD_FACTOR; // all other fields defaulted
}

/**
 * Constructs a new <tt>HashMap</tt> with the same mappings as the
 * specified <tt>Map</tt>.  The <tt>HashMap</tt> is created with
 * default load factor (0.75) and an initial capacity sufficient to
 * hold the mappings in the specified <tt>Map</tt>.
 *
 * @param   m the map whose mappings are to be placed in this map
 * @throws  NullPointerException if the specified map is null
 */
public HashMap(Map<? extends K, ? extends V> m) {
    this.loadFactor = DEFAULT_LOAD_FACTOR;
    putMapEntries(m, false);
}

查詢

/**
 * 返回指定 key 所對應的 value 值,當不存在指定的 key 時,返回 null。
 *
 * 當返回 null 的時候並不代表哈希表中不存在這種關係的映射,有可能對於指定的 key,其對應的值就是 null。
 * 所以能夠經過 containsKey 來區分這兩種狀況。
 */
public V get(Object key) {
    Node<K,V> e;
    return (e = getNode(hash(key), key)) == null ? null : e.value;
}

/**
 * 1.首先經過 key 的哈希值找到其所在的哈希桶
 * 2.對於 key 所在的哈希桶只有一個元素,此時就是 key 對應的節點,
 * 3.對於 key 所在的哈希桶超過一個節點,此時分兩種狀況:
 *     若是這是一個 TreeNode,代表經過紅黑樹存儲,在紅黑樹中查找
 *     若是不是一個 TreeNode,代表經過鏈表存儲(鏈地址法),在鏈表中查找
 * 4.查找不到相應的 key,返回 null
 */
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;
}

<span id="存儲">存儲</span>

/**
 * 存儲指定的批量的映射關係對
 * @param m 指定的批量的映射關係對
 * @param evict 判斷是否移除,最初構造映射關係時爲false,不然爲 true(爲 true 時會執行 afterNodeInsertion 函數)
 */
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);
            //超過所能容納的 key-value 對的極限,置 threshold 爲2的冪次方,在 resize 的時候會用到
            //因爲此時哈希表爲 null,所以在存儲的時候必定會執行 resize,具體可看 putVal 函數
            if (t > threshold)
                threshold = tableSizeFor(t);
        //存儲的映射關係對的數量大於所能容納的 key-value 對的極限時,擴容
        } 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 V put(K key, V value) {
    return putVal(hash(key), key, value, false, true);
}

/**
 * * @param onlyIfAbsent if true, don't change existing value
 *   @param evict 判斷是否移除,爲 false時,表示哈希表正在建立
 *
 * 1.判斷哈希表 table 是否爲空,是的話進行擴容操做
 * 2.根據鍵 key 計算獲得的 哈希桶數組索引,若是 table[i] 爲空,那麼直接新建節點
 * 3.判斷 table[i] 的首個元素是否等於 key,若是是的話就更新舊的 value 值
 * 4.判斷 table[i] 是否爲 TreeNode,是的話即爲紅黑樹,直接在樹中進行插入
 * 5.遍歷 table[i],遍歷過程發現 key 已經存在,更新舊的 value 值,不然進行插入操做,插入後發現鏈表長度大於8,則將鏈表轉換爲紅黑樹
 */
final V putVal(int hash, K key, V value, boolean onlyIfAbsent,
               boolean evict) {
    Node<K,V>[] tab; Node<K,V> p; int n, i;
    //哈希表 table 爲空,進行擴容操做
    if ((tab = table) == null || (n = tab.length) == 0)
        n = (tab = resize()).length;
    // tab[i] 爲空,直接新建節點
    if ((p = tab[i = (n - 1) & hash]) == null)
        tab[i] = newNode(hash, key, value, null);
    else {
        Node<K,V> e; K k;
        //tab[i] 首個元素即爲 key,更新舊值
        if (p.hash == hash &&
            ((k = p.key) == key || (key != null && key.equals(k))))
            e = p;
        //當前節點爲 TreeNode,在紅黑樹中進行插入
        else if (p instanceof TreeNode)
            e = ((TreeNode<K,V>)p).putTreeVal(this, tab, hash, key, value);
        else {
            //遍歷 tab[i],key 已經存在,更新舊的 value 值,不然進行插入操做,插入後鏈表長度大於8,將鏈表轉換爲紅黑樹
            for (int binCount = 0; ; ++binCount) {
                if ((e = p.next) == null) {
                    p.next = newNode(hash, key, value, null);
                    //鏈表長度大於8
                    if (binCount >= TREEIFY_THRESHOLD - 1) // -1 for 1st
                        treeifyBin(tab, hash);
                    break;
                }
                // key 已經存在
                if (e.hash == hash &&
                    ((k = e.key) == key || (key != null && key.equals(k))))
                    break;
                p = e;
            }
        }
        //key 已經存在,更新舊值
        if (e != null) { // existing mapping for key
            V oldValue = e.value;
            if (!onlyIfAbsent || oldValue == null)
                e.value = value;
            afterNodeAccess(e);
            return oldValue;
        }
    }
    //HashMap插入元素代表進行告終構性調整
    ++modCount;
    //實際鍵值對數量超過 threshold,進行擴容操做
    if (++size > threshold)
        resize();
    afterNodeInsertion(evict);
    return null;
}

擴容

/**
 * 初始化或者對哈希表進行擴容操做。若是當前哈希表爲空,則根據字段閾值中的初始容量進行分配。
 * 不然,由於咱們擴容兩倍,那麼對於桶中的元素要麼在原位置,要麼在原位置再移動2次冪的位置。
 */
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; // double threshold
    }
    else if (oldThr > 0) // initial capacity was placed in threshold
        //調用了HashMap的帶參構造器,初始容量用threshold替換,
        //在帶參構造器中,threshold的值爲 tableSizeFor() 的返回值,也就是2的冪次方,而不是 capacity * load factor
        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) {
                //將原哈希桶置空,以便GC
                oldTab[j] = null;
                //當前節點不是以鏈表形式存在,直接計算其應放置的新位置
                if (e.next == null)
                    newTab[e.hash & (newCap - 1)] = e;
                //當前節點是TreeNode
                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;
                        }
                        //原索引 + oldCap
                        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;
}

    由於哈希表使用2次冪的拓展(指長度拓展爲原來的2倍),因此在擴容的時候,元素的位置要麼在原位置,要麼在原位置再移動2次冪的位置。爲何是這麼一個規律呢?咱們假設 n 爲 table 的長度,圖(a)表示擴容前的key1和key2兩種key肯定索引位置的示例,圖(b)表示擴容後key1和key2兩種key肯定索引位置的示例,其中hash1是key1對應的哈希與高位運算結果。 元素在從新計算hash以後,由於n變爲2倍,那麼n-1的mask範圍在高位多1bit(紅色),所以新的index就會發生這樣的變化: 所以,咱們在擴容的時候,只須要看看原來的hash值新增的那個 bit 是1仍是0就行了,是0的話索引沒變,是1的話索引變成「原索引+oldCap」,能夠看看下圖爲16擴充爲32的resize示意圖:

刪除

/**
 * 刪除指定的 key 的映射關係
 */
public V remove(Object key) {
    Node<K,V> e;
    return (e = removeNode(hash(key), key, null, false, true)) == null ?
        null : e.value;
}

/**Java
 *
 * 1.根據 key 的哈希值在哈希桶中查找是否存在這個包含有這個 key 的節點
 *      鏈表頭節點是要查找的節點
 *      節點是TreeNode,在紅黑樹中查找
 *      在鏈表中進行查找
 * 2.若是查找到對應的節點,進行刪除操做
 *      從紅黑樹中刪除
 *      將鏈表頭節點刪除
 *      在鏈表中刪除
 *
 * @param hash key 的 hash 值
 * @param key 指定的 key
 * @param value 當 matchhValue 爲真時,則要匹配這個 value
 * @param matchValue 爲真而且與 value 相等時進行刪除
 * @param movable if false do not move other nodes while removing
 * @return the node, or null if none
 */
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) {
            //節點爲TreeNode,在紅黑樹中查找是否存在指定的key
            if (p instanceof TreeNode)
                node = ((TreeNode<K,V>)p).getTreeNode(hash, key);
            else {
                //在鏈表中查找是否存在指定的key
                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;
}

/**
 * 刪除全部的映射關係
 */
public void clear() {
    Node<K,V>[] tab;
    modCount++;
    if ((tab = table) != null && size > 0) {
        size = 0;
        for (int i = 0; i < tab.length; ++i)
            //置 null 以便 GC
            tab[i] = null;
    }
}

問題

  • 對於new HashMap(18),那麼哈希桶數組的大小是多少
  • HashMap 要求哈希桶數組的長度是2的冪次方,這麼設計的目的是爲何
  • HashMap 什麼時候對哈希桶數組開闢內存
  • 哈希函數是如何設計的,這麼設計的意圖是什麼
  • HashMap 擴容的過程,擴容時候對 rehash 進行了什麼優化

參考資料

Java 8系列之從新認識HashMap

相關文章
相關標籤/搜索