HashMap 的使用及源碼解析

1. 概述

在Android開發中,HashMap也是常用的集合類,一直以來只是知道怎麼用,以及HashMap是線程不安全的,但是對於內部是如何實現卻沒有去關注過。此篇將對HashMap的源碼進行解析,進一步瞭解HashMap的實現原理。在JDK1.8之前的版本HashMap的實現和JDK1.8的HashMap實現方式存在較大差異,這裏只解析JDK1.8中HashMap的源碼。

2. HashMap 的使用

先看以下例子:

package cn.zzw.linkhashmap;

import java.util.*;


public class TestHashMap {
    public static void main(String[] args) {
        HashMap<Integer, String> hm = new HashMap<>();
        hm.put(0, "zzw0");
        hm.put(1, "zzw1");
        hm.put(2, "zzw2");
        hm.put(null, "zzwNull");
        hm.put(3, "zzw3");
        hm.put(7, "zzw7");
        hm.put(4, "zzw4");
        hm.put(5, "zzw5");
        hm.put(6, "zzw6");
        hm.put(8, null);
        Set<Map.Entry<Integer, String>> set = hm.entrySet();
        Iterator<Map.Entry<Integer, String>> iterator = set.iterator();
        while (iterator.hasNext()) {
            Map.Entry entry = iterator.next();
            Integer key = (Integer) entry.getKey();
            String value = (String) entry.getValue();
            System.out.println("key:" + key + ",value:" + value);
        }
    }
}

運行結果:

key:null,value:zzwNull
key:1,value:zzw1
key:2,value:zzw2
key:3,value:zzw3
key:4,value:zzw4
key:5,value:zzw5
key:6,value:zzw6
key:7,value:zzw7
key:8,value:null

此例子中包含HashMap的創建,數據的添加,以及對HashMap中的數據進行迭代。

HashMap的構造方法:

Constructor and Description
HashMap()

構造一個空的 HashMap ,默認初始容量(16)和默認負載係數(0.75)。

HashMap(int initialCapacity)

構造一個空的 HashMap具有指定的初始容量和默認負載因子(0.75)。

HashMap(int initialCapacity, float loadFactor)

構造一個空的 HashMap具有指定的初始容量和負載因子。

HashMap(Map<? extends K,? extends V> m)

構造一個新的 HashMap與指定的相同的映射 Map 。

HashMap 常用的API有如下:

 
Modifier and Type Method and Description
void clear()

從這張地圖中刪除所有的映射。

Set<Map.Entry<K,V>> entrySet()

返回此地圖中包含的映射的Set視圖。

V get(Object key)

返回到指定鍵所映射的值,或 null如果此映射包含該鍵的映射。

boolean isEmpty()

如果此地圖不包含鍵值映射,則返回 true 。

Set<K> keySet()

返回此地圖中包含的鍵的Set視圖。

V put(K key, V value)

將指定的值與此映射中的指定鍵相關聯。

V remove(Object key)

從該地圖中刪除指定鍵的映射(如果存在)。

boolean remove(Object key, Object value)

僅當指定的密鑰當前映射到指定的值時刪除該條目。

int size()

返回此地圖中鍵值映射的數量。

 以上方法包含了平時在工作中HashMap常用的方法。詳細的API文檔可以參考:https://docs.oracle.com/javase/8/docs/api/

從以上的例子中可以看出:

HashMap存儲的是key-value的鍵值對,允許key爲null,也允許value爲null。

3. HashMap 的源碼解析

3.1 基本屬性:

默認初始容量爲 16 和默認負載因子爲 0.75。

    // 默認初始容量爲16,必須爲2的冪
    static final int DEFAULT_INITIAL_CAPACITY = 1 << 4; // aka 16

    
    // 最大容量,必須爲2的冪
    static final int MAXIMUM_CAPACITY = 1 << 30;


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


    // 鏈表節點轉換紅黑樹節點的閾值, 9個節點轉
    static final int TREEIFY_THRESHOLD = 8;


    // 紅黑樹節點轉換鏈表節點的閾值, 6個節點轉
    static final int UNTREEIFY_THRESHOLD = 6;


    // 轉紅黑樹時, table的最小長度
    static final int MIN_TREEIFY_CAPACITY = 64;

3.2 構造方法:

3.2.1 無參構造方法

    public HashMap() {
        this.loadFactor = DEFAULT_LOAD_FACTOR; // all other fields defaulted
    }

在無參構造方法中,將負載因子賦值爲默認的負載因子0.75。

3.2.2 指定容量大小以及負載因子的構造方法:

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

首先判斷指定的容量值 initialCapacity 是否大於0,如果小於0,則拋出異常 IllegalArgumentException。當 initialCapacity 大於0以後,繼續判斷 initialCapacity 是否超過允許設置的最大值,如果比允許設置的最大值還大,則把initialCapacity 的值賦值爲允許設置的最大值 MAXIMUM_CAPACITY。

其次判斷指定的負載因子的值是否是一個數字以及值是否大於0,否則拋出異常。

最後,對 threshold 進行賦值,threshold 代表下次擴容閥值。這裏通過調用方法 tableSizeFor(initialCapacity) 進行賦值,方法的參數爲 HashMap 的容量。

tableSizeFor 方法:返回大於輸入參數且最近的2的整數次冪的數。比如輸入10,11或者15,則都返回16。

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

3.2.3 指定容量大小的構造方法:

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

 在此構造方法中,調用的 3.2.2 中的構造方法。負載因子爲默認的負載因子0.75 。

3.2.4 有一個Map類型參數的構造方法

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

此構造方法中,將默認的負載因子(0.75)賦值給 loadFactor 。調用 PutMapEntries() 來完成HashMap的初始化賦值過程。(這裏先不探究 PutMapEntries()方法。)

3.3 Put 方法:

在平時開發過程中,最常用的HashMap進行初始化方法爲 3.2.1 無參構造方法 。當對 HashMap 進行初始化後,就該對HashMap 進行賦值了。put() 方法就是用於對HashMap中存入key-value形式的值。

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

key,value都爲泛型,通過2中HashMap的用例,可以看出 key,value的值可以爲 null 。在put 方法中調用的 putVal(),在此方法調用前,先對key調用了 hash()方法。

hash() 方法:

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

key不爲空的話,拿到 key 的 hashCode 值:h = key.hashCode(),並通過 (h = key.hashCode()) ^ (h >>> 16) 計算 key 的 hash 值。

putVal() 方法:

    final V putVal(int hash, K key, V value, boolean onlyIfAbsent,
                   boolean evict) {
        Node<K,V>[] tab; Node<K,V> p; int n, i;    //1
        if ((tab = table) == null || (n = tab.length) == 0) //2
            n = (tab = resize()).length;
        if ((p = tab[i = (n - 1) & hash]) == null)    //3
            tab[i] = newNode(hash, key, value, null);
        else {             
            Node<K,V> e; K k;    //4
            if (p.hash == hash &&
                ((k = p.key) == key || (key != null && key.equals(k))))    //5
                e = p;
            else if (p instanceof TreeNode)    //6
                e = ((TreeNode<K,V>)p).putTreeVal(this, tab, hash, key, value);    
            else {
                for (int binCount = 0; ; ++binCount) {    //7
                    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   //8
                V oldValue = e.value;
                if (!onlyIfAbsent || oldValue == null)
                    e.value = value;
                afterNodeAccess(e);
                return oldValue;
            }
        }
        ++modCount;   //9
        if (++size > threshold)  //10
            resize();
        afterNodeInsertion(evict);
        return null;
    }

下面逐一解釋以上的代碼:

註釋1:聲明變量

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

Node 是 HashMap 中一個靜態類,是一個帶有3個值,hash、key、value 和另外一個Node 對象引用的HashMap子元素結構,裝的每個 key-value 就用一個 Node 對象存放。

註釋2:table 爲 Node 類型的數組。

transient Node<K,V>[] table;

將 table 賦值給變量 tab ,並判斷 tab 是否爲空。一開始 table 是爲空的,所以會執行:

n = (tab = resize()).length;

調用了方法 resize(),返回大小爲16的Node數組。resize()留着後面解析。這裏 n = 16。tab 爲大小爲 16 的 Node 數組。

註釋3:

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

i 取值爲範圍爲 0~ n-1,初始時候 n = 16 ,雖然 tab 不爲空,但是裏面的值都爲 null,所以會執行到:

tab[i] = newNode(hash, key, value, null);

方法newNode()的作用是:new一個節點Node,放在數組裏,i 是上一步中計算的索引。

    Node<K,V> newNode(int hash, K key, V value, Node<K,V> next) {
        return new Node<>(hash, key, value, next);
    }

註釋4:

如果當前存的 key計算出來的索引值已經存過了:(p = tab[i = (n - 1) & hash]) 不爲空。意味着發生了 hash 衝突,從註釋4開始就是處理衝突的。創建了 Node 類型的元素 e,以及泛型 k。

Node<K,V> e; K k;

註釋5:

            if (p.hash == hash &&
                ((k = p.key) == key || (key != null && key.equals(k))))
                e = p;

p 是發生衝突時,數組該索引位置的元素。

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

判斷 p 的 key 與新元素的 key 是否相等。

((k = p.key) == key || (key != null && key.equals(k)))

判斷 p 的 key 的 hash 值與新元素的 hash 是否相等。

如果上面的判斷都相等,則表示存了一樣的 key,直接賦值給註釋4創建的 e。

註釋6:

p instanceof TreeNode

判斷 p 是否是 TreeNode 類型,如果是 TreeNode類型,則執行:

e = ((TreeNode<K,V>)p).putTreeVal(this, tab, hash, key, value); 

TreeNode 是靜態的內部類,就是紅黑樹的節點,如果是紅黑樹的節點,則調用方法 putTreeVal() 往紅黑樹中添加元素。

註釋7:

如果 key 不同,且不是紅黑樹,則通過循環遍歷到鏈表的尾部。

                for (int binCount = 0; ; ++binCount) {
                    if ((e = p.next) == null) {
                        ...
                        ...
                    }
                    if (e.hash == hash &&
                        ((k = e.key) == key || (key != null && key.equals(k))))
                        break;
                    p = e;
                }

當遍歷到鏈表的尾部後,在尾部插入新的節點。

p.next = newNode(hash, key, value, null);

 如果鏈表的長度超過 TREEIFY_THRESHOLD(8),則調用方法 treeifyBin() 將鏈表轉換爲紅黑樹:

    /**
     * Replaces all linked nodes in bin at index for given hash unless
     * table is too small, in which case resizes instead.
     */
    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);
        }
    }

註釋8:

最後判斷 e 是不是空,當 e 不爲空,則將新的值 value 進行覆蓋,e 爲空,則就是無相同的 key 且將數據成功的插入。

            if (e != null) { // existing mapping for key
                V oldValue = e.value;
                if (!onlyIfAbsent || oldValue == null)
                    e.value = value;
                afterNodeAccess(e);
                return oldValue;
            }

註釋9: 

modCount 是用於記錄數據結構變動的次數,操作一次則加1。

transient int modCount;

註釋10:

        if (++size > threshold)
            resize();

添加成功一次後,size 加 1。這裏 size 代表 HashMap 存儲的 key-value 對的個數。

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

然後將 size 與擴容的閾值 threshold 進行對比,size 大於 threshold,則調用方法 resize() 進行擴容。

3.4 resize 方法:

resize 方法在 HashMap 的源碼中是負責進行擴容的,返回的是一個新的 Node 類型的數組。

    final Node<K,V>[] resize() {
        Node<K,V>[] oldTab = table;    //1
        int oldCap = (oldTab == null) ? 0 : oldTab.length;
        int oldThr = threshold;
        int newCap, newThr = 0;
        if (oldCap > 0) {       //2
            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) //3 initial capacity was placed in threshold
            newCap = oldThr;
        else {               //4 zero initial threshold signifies using defaults
            newCap = DEFAULT_INITIAL_CAPACITY;
            newThr = (int)(DEFAULT_LOAD_FACTOR * DEFAULT_INITIAL_CAPACITY);
        }
        if (newThr == 0) {    //5
            float ft = (float)newCap * loadFactor;
            newThr = (newCap < MAXIMUM_CAPACITY && ft < (float)MAXIMUM_CAPACITY ?
                      (int)ft : Integer.MAX_VALUE);
        }
        threshold = newThr;    //6
        @SuppressWarnings({"rawtypes","unchecked"})
            Node<K,V>[] newTab = (Node<K,V>[])new Node[newCap];
        table = newTab;
        if (oldTab != null) {    //7
            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;
    }

註釋1:

創建 oldTab 來存儲 Node<K,V> 類型的數組 table;創建 oldCap 來存儲舊的容量;創建 oldThr 來存儲擴容的閾值 threshold;

        Node<K,V>[] oldTab = table;
        int oldCap = (oldTab == null) ? 0 : oldTab.length;
        int oldThr = threshold;

創建 newCap,newThr 來存儲新的容量以及新的擴容閾值,並做初始化爲 0。

int newCap, newThr = 0;

註釋2:

當舊容量大於0,則該 HashMap 中已經有元素。

        if (oldCap > 0) {
            ...
            ...
        }

如果舊容量超過最大容量,則擴容的閾值爲 Integer 的最大值,就不在進行擴容了:

            if (oldCap >= MAXIMUM_CAPACITY) {
                threshold = Integer.MAX_VALUE;
                return oldTab;
            }

如果容量沒有超過最大值,則擴充爲原來的2倍,並且新的擴容閾值也擴充爲原來的兩倍:

            else if ((newCap = oldCap << 1) < MAXIMUM_CAPACITY &&
                     oldCap >= DEFAULT_INITIAL_CAPACITY)
                newThr = oldThr << 1; // double threshold

註釋3:

如果容量 oldCap 小於等於0,則會進行判斷註釋3。當用 3.2.2 指定容量大小以及負載因子的構造方法對 HashMap 進行初始化,table 大小爲0,容量爲調用方法 tableSizeFor 後返回的大小。

        else if (oldThr > 0) // initial capacity was placed in threshold
            newCap = oldThr;

註釋4:

如果用3.2.1 無參構造方法對HashMap進行初始化,則會走到註釋4:

        else {               // zero initial threshold signifies using defaults
            newCap = DEFAULT_INITIAL_CAPACITY;
            newThr = (int)(DEFAULT_LOAD_FACTOR * DEFAULT_INITIAL_CAPACITY);
        }

註釋5:

如果新的閾值爲0,則重新設置閾值:

        if (newThr == 0) {
            float ft = (float)newCap * loadFactor;
            newThr = (newCap < MAXIMUM_CAPACITY && ft < (float)MAXIMUM_CAPACITY ?
                      (int)ft : Integer.MAX_VALUE);
        }

註釋6: 

把 HashMap 閾值設置爲新的閾值,並且初始化新的數組,並將初始化後的數組賦值給 table。如果是進行第一次初始化,則不會再走後面的代碼,resize 就只走到如下代碼,則擴容後的新數組。

        threshold = newThr;
        @SuppressWarnings({"rawtypes","unchecked"})
            Node<K,V>[] newTab = (Node<K,V>[])new Node[newCap];
        table = newTab;

註釋7: 

當 HashMap 不爲空時候,所有在oldTab上的元素通過遍歷轉移到新的table中。

首先創建臨時變量:

Node<K,V> e;

並將數組下標爲 j 的值賦值給變量 e,當 e 不爲空的時候,將舊值置爲空:

                if ((e = oldTab[j]) != null) {
                    oldTab[j] = null;
                ...
                ...

如果 e 沒有下一個元素,即鏈表只有一個元素,則直接進行賦值:

                    if (e.next == null)
                        newTab[e.hash & (newCap - 1)] = e;

如果 e 是紅黑樹的節點,則將樹轉移到 newTab 中:

                    else if (e instanceof TreeNode)
                        ((TreeNode<K,V>)e).split(this, newTab, j, oldCap);

如果是鏈表不爲空,則對鏈表進行復制,首先 5 個 Node 類型的引用:

                        Node<K,V> loHead = null, loTail = null;
                        Node<K,V> hiHead = null, hiTail = null;
                        Node<K,V> next;

接着採用do-while語句進行遍歷鏈表中的節點:

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

在此循環中,通過判斷 (e.hash & oldCap) == 0 的結果,執行不同的邏輯:

當 (e.hash & oldCap) == 0 的值爲 true,將節點放入鏈表 lo;

當 (e.hash & oldCap) == 0 的值爲 false,將節點放入鏈表 hi;

通過此循環後,節點就被放入了兩個新的鏈表之中,並且

                        if (loTail != null) {
                            loTail.next = null;
                            newTab[j] = loHead;
                        }
                        if (hiTail != null) {
                            hiTail.next = null;
                            newTab[j + oldCap] = hiHead;
                        }

如果鏈表 lo 非空,則把鏈表放到新 table 的 j 位置上;

如果鏈表 hi 非空,則把鏈表放到新 table 的 j+oldCap 位置上;

這樣就完成了擴容,並返回一個新的數組。

3.5 get 方法:

get 方法用於通過 key 的值去查找 HashMap 中對應的節點的值:

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

通過 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) {    //1
            if (first.hash == hash && //2 always check first node
                ((k = first.key) == key || (key != null && key.equals(k))))
                return first;
            if ((e = first.next) != null) {    //3
                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;
    }

註釋1:

(tab = table) != null && (n = tab.length) > 0 &&
            (first = tab[(n - 1) & hash]) != null

將 table 賦值給臨時變量 tab,並且數組的長度大於 0,並且傳入的 key 的 hash 值在數組中找到不爲空的的元素:

註釋2:

            if (first.hash == hash && // always check first node
                ((k = first.key) == key || (key != null && key.equals(k))))
                return first;

在 hash 值相等的情況下,判斷key對象是否相等:是否爲同一對象(==)/ 不同對象調用equals()進行比較。

註釋3:

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

如果是紅黑樹的節點,則從紅黑樹中獲取:

        final TreeNode<K,V> getTreeNode(int h, Object k) {
            return ((parent != null) ? root() : this).find(h, k, null);
        }

 紅黑樹尋找節點的方法:

        final TreeNode<K,V> find(int h, Object k, Class<?> kc) {
            TreeNode<K,V> p = this;
            do {
                int ph, dir; K pk;
                TreeNode<K,V> pl = p.left, pr = p.right, q;
                if ((ph = p.hash) > h)
                    p = pl;
                else if (ph < h)
                    p = pr;
                else if ((pk = p.key) == k || (k != null && k.equals(pk)))
                    return p;
                else if (pl == null)
                    p = pr;
                else if (pr == null)
                    p = pl;
                else if ((kc != null ||
                          (kc = comparableClassFor(k)) != null) &&
                         (dir = compareComparables(kc, k, pk)) != 0)
                    p = (dir < 0) ? pl : pr;
                else if ((q = pr.find(h, k, kc)) != null)
                    return q;
                else
                    p = pl;
            } while (p != null);
            return null;
        }

如果是鏈表,則通過 do-while 循環,從鏈表中取出節點。

4. 總結

HashMap 中,最常用的是無參數的構造方法。通過無參數的構造方法,默認創建一個 Node 類型的空數組,且默認設置負載因子爲0.75。

當第一次調用方法 put() 添加元素的時候,會創建一個長度大小爲 16 的數組,且設置擴容閾值爲 12(16*0.75)。

當 HashMap 的節點個數不大於 8 的時候,底層是數組+鏈表來實現,當 HashMap 的節點個數大於 8 的時候,鏈表將轉化爲紅黑樹的結構,HashMap 每次擴容都擴容爲原容量的兩倍。

由於 HashMap 會進行 resize 操作,在resize 操作中會重新計算元素的 index,在多線程操作中存在多線程的不安全問題。

參考:

https://www.cnblogs.com/zhaojj/p/7805376.html

https://github.com/LRH1993/android_interview/blob/master/java/basis/hashmap.md

https://segmentfault.com/a/1190000015812438?utm_source=tag-newest

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