HashMap源碼分析

前言

面試一般都會問到HashMap

整理內容自慕課網
https://coding.imooc.com/lesson/337.html#mid=24128

參考博客:https://www.cnblogs.com/aspirant/p/8906018.html

內容講的是HashTable,裏面數據結構和如何擴容說得挺好

內容

  • 圖解數據結構
  1. 圖解說明數據結構基礎
  2. 圖解說明HashMap原理
  • 源碼分析
  1. 源碼分析HashMap的創建以及擴容
  2. 節點的插入、查詢與刪除
  3. 如何提高散列以及衝突的解決辦法

圖解說明HashMap

HashMap是如何實現快速索引的?

數組

數組的本質是一塊連續的內存空間,因爲內存空間連續,我們只要知道首地址的位置,就能很快定位所有數據,所以數組的有點很明顯,就是通過下標可以快速尋址

缺點也是明顯的,就是對於有序的數據,如果想要插入,就要移動大量的位置

單鏈表
node {
   T data;
   node next;
}

插入刪除方便,查詢O(n)

HashMap

HashMap既要插入高效,又要查詢高效,顯然就是結合了數組和鏈表二者的優點

爲了快速定位,又要插入數據,如果保持插入的動作不變,那麼爲了能夠定位,我們就需要知道插入的值和數組下標之間的關係

假設數據是一個int類型的數組

pos = key % size

key就是插入的數據,size是數組的大小,pos就是下標

那麼插入和查找的時候都需要通過這個求模操作

但是這很顯然有一個問題

兩個插入的值100和200對一個size爲10的數組求模,得到的結果都是0,這顯然是不允許出現的情況

這就涉及到了HashMap的衝突問題

要解決這一衝突,有一個很簡單的辦法,就是在同一個下標用單鏈表來進行擴展

就上面的例子來說就是100的這個節點位置有一個指向200的指針

查找時將有一個比較值並且比較其next的過程

那麼問題就又繞回來了,單鏈表查詢低效(但其實夠用了)

在JDK1.8版本中對這一問題做了優化,將單鏈表過長的時候將轉化爲紅黑樹以提高查詢速率,這裏不對紅黑樹做講解

HashMap源碼分析

resize與hash比較

構造一個HashMap

public static void main(String[] args) {
    Map<String, String> map = new HashMap<>();
    map.put("100", "test");
}

查看它的構造方法

/**
 * Constructs an empty <tt>HashMap</tt> with the default initial capacity
 * (16) and the default load factor (0.75).
 */
public HashMap() {
    this.loadFactor = DEFAULT_LOAD_FACTOR; // all other fields defaulted
}

對成員變量loadFactor負載因子賦值0.75f

再來查看HashMap的put操作

/**
 * Associates the specified value with the specified key in this map.
 * If the map previously contained a mapping for the key, the old
 * value is replaced.
 *
 * @param key key with which the specified value is to be associated
 * @param value value to be associated with the specified key
 * @return the previous value associated with <tt>key</tt>, or
 *         <tt>null</tt> if there was no mapping for <tt>key</tt>.
 *         (A <tt>null</tt> return can also indicate that the map
 *         previously associated <tt>null</tt> with <tt>key</tt>.)
 */
public V put(K key, V value) {
    return putVal(hash(key), key, value, false, true);
}

裏面是一個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.
 * @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;
}

putVal的幾件事情

  1. 判斷table是否爲空 進行resize
  2. hash判斷是直接插入還是鏈表插入

resize方法有三個重要的參數:負載因子、容量、閾值

下面是初始化時的參數

newCap = DEFAULT_INITIAL_CAPACITY; // 1 << 4 aka 16
newThr = (int)(DEFAULT_LOAD_FACTOR * DEFAULT_INITIAL_CAPACITY);

噹噹前的table大小超過閾值的時候就會擴容

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
}

擴容是舊的容量左移一位

再看一下它的hash判斷

if ((p = tab[i = (n - 1) & hash]) == null)

n是table的大小 大小減1之後hash得到的i(這裏涉及hash的計算之後再說 hash自然是根據內容得到的)

面試問題:爲什麼初始大小爲2的倍數

  1. 最主要的是:2的倍數減1之後會得到後面全爲1的二進制位,hash與運算可以有多種結果,即提高散列度
  2. 通用的,減少內存分頁的碎片
  3. 計算機最擅長與運算等
如何Hash
public V put(K key, V value) {
    return putVal(hash(key), key, value, false, true);
}

putVal的第一個參數就是hash,那麼如何得到這個根據key獲取到的hash值呢

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

這裏邏輯很簡單

  1. 首先判空,如果爲空則直接返回0
  2. 如果不爲空則通過native方法hasCode獲取int值
  3. 與這個值右移十六位之後的結果進行異或運算

這裏的異或操作也是爲了提高散列度…至於爲什麼我也不知道

這是面試問題中Hash函數如何減少衝突的一個回答

衝突的解決

其實就是

if ((p = tab[i = (n - 1) & hash]) == null)

這個else裏面的內容了

這裏簡單梳理一下邏輯

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

這裏有三種可能

  1. 插入的新節點的hash與key值都與當前節點相同
  2. 舊節點是一個黑紅樹的節點
  3. 舊節點是一個單鏈表的節點

插入屬於數據結構的知識了,這裏看一下單鏈表到紅黑樹轉化的邏輯

if (binCount >= TREEIFY_THRESHOLD - 1) // -1 for 1st
                            treeifyBin(tab, hash);

名字非常直觀了 如果單鏈表的長度超過了樹化的閾值那麼就進行紅黑樹化

默認的樹化閾值爲8

擴容與非擴容後的內存排布

來分析一下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
            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;

前面都在進行初始化

如果oldTable是有值的,那麼就要把oldTable的節點給複製到newTable

這裏有三個判斷

  1. e.next == null 也就是沒有衝突的情況
  2. e instanceof TreeNode 衝突解決是紅黑樹的形式
  3. 衝突解決是單鏈表的形式

分支選擇來完成複製

  1. 沒有衝突
newTab[e.hash & (newCap - 1)] = e;

根據hash來確定位置 這裏的下標是newCap-1來hash的,這和putVal的hash判斷一致
2. 紅黑樹的split 略
3. 單鏈表的處理

//如果擴容後,元素的index依然與原來一樣,那麼使用這個head和tail指針
Node<K,V> loHead = null, loTail = null
//如果擴容後,元素的index=index+oldCap,那麼使用這個head和tail指針
Node<K,V> hiHead = null, hiTail = null
Node<K,V> next;
do {
    next = e.next;
    //這個地方直接通過hash值與oldCap進行與操作得出元素在新數組的index
    if ((e.hash & oldCap) == 0) {
        if (loTail == null)
            loHead = e;
        else
            loTail.next = e;
        //tail指針往後移動一位,維持順序    
        loTail = e;
    }
    else {
        if (hiTail == null)
            hiHead = e;
        else
            hiTail.next = e;
        //tail指針往後移動一位,維持順序    
        hiTail = e;
    }
} while ((e = next) != null);
if (loTail != null) {
    loTail.next = null;
    //還是原來的index
    newTab[j] = loHead;
}
if (hiTail != null) {
    hiTail.next = null;
    //index = index + oldCap
    newTab[j + oldCap] = hiHead;

這裏這麼做可以保證它與舊的鏈表順序相同

HashMap的查詢
public static void main(String[] args) {
    Map<String, String> map = new HashMap<>();
    map.put("100", "test");
    map.get("100");
}
/**
     * Returns the value to which the specified key is mapped,
     * or {@code null} if this map contains no mapping for the key.
     *
     * <p>More formally, if this map contains a mapping from a key
     * {@code k} to a value {@code v} such that {@code (key==null ? k==null :
     * key.equals(k))}, then this method returns {@code v}; otherwise
     * it returns {@code null}.  (There can be at most one such mapping.)
     *
     * <p>A return value of {@code null} does not <i>necessarily</i>
     * indicate that the map contains no mapping for the key; it's also
     * possible that the map explicitly maps the key to {@code null}.
     * The {@link #containsKey containsKey} operation may be used to
     * distinguish these two cases.
     *
     * @see #put(Object, Object)
     */
    public V get(Object key) {
        Node<K,V> e;
        return (e = getNode(hash(key), key)) == null ? null : e.value;
    }

調用getNode方法

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

這裏也沒什麼特別的,就和平時寫業務邏輯的代碼一樣判空之類操作

若都不爲空爲比較key值,若first不等則分別按照紅黑樹和單鏈表來繼續比較

HashMap刪除
/**
     * Removes the mapping for the specified key from this map if present.
     *
     * @param  key key whose mapping is to be removed from the map
     * @return the previous value associated with <tt>key</tt>, or
     *         <tt>null</tt> if there was no mapping for <tt>key</tt>.
     *         (A <tt>null</tt> return can also indicate that the map
     *         previously associated <tt>null</tt> with <tt>key</tt>.)
     */
    public V remove(Object key) {
        Node<K,V> e;
        return (e = removeNode(hash(key), key, null, false, true)) == null ?
            null : e.value;
    }

看一下removeNode

/**
     * Implements Map.remove and related methods
     *
     * @param hash hash for key
     * @param key the key
     * @param value the value to match if matchValue, else ignored
     * @param matchValue if true only remove if value is equal
     * @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) {
                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;
    }

刪除的邏輯開始和查找一樣,找到之後獲取這個node

然後分別根據無衝突、黑紅樹、單鏈表三種分支來操作刪除

共同需要做的就是–size等

HashMap的序列化

HashMap的序列化主要是調用了writeObject方法

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