HashMap-你可能需要知道這些

HashMap是Android程序員(當(dāng)然也包括Java程序員)經(jīng)常使用的映射數(shù)據(jù)類型,伴隨著JDK的版本更新,JDK1.8相比1.7對(duì)HashMap的底層實(shí)現(xiàn)了一些優(yōu)化,尤其是紅黑樹這個(gè)點(diǎn)(現(xiàn)在面試的時(shí)候基本都會(huì)問到這個(gè)問題),本博文結(jié)合JDK1.8源碼分析下HashMap的實(shí)現(xiàn)原理。

1.簡介

1.1 哈希算法

什么是哈希算法呢?

哈希算法將任意長度的二進(jìn)制值映射為較短的固定長度的二進(jìn)制值,這個(gè)小的二進(jìn)制值稱為哈希值。哈希值是一段數(shù)據(jù)唯一且極其緊湊的數(shù)值表示形式。如果散列一段明文而且哪怕只更改該段落的一個(gè)字母,隨后的哈希都將產(chǎn)生不同的值。要找到散列為同一個(gè)值的兩個(gè)不同的輸入,在計(jì)算上是不可能的,所以數(shù)據(jù)的哈希值可以檢驗(yàn)數(shù)據(jù)的完整性。一般用于快速查找和加密算法。

1.2 解決hash沖突

HashMap使用鏈地址法來解決hash沖突,即數(shù)組+鏈表的組合,JDK1.8之后才引入了紅黑樹進(jìn)行存儲(chǔ)優(yōu)化。
每個(gè)數(shù)組元素上都是一個(gè)鏈表結(jié)構(gòu),當(dāng)數(shù)據(jù)被hash后得到數(shù)組的下標(biāo),把數(shù)據(jù)存儲(chǔ)到對(duì)應(yīng)下標(biāo)的鏈表上。

1.3 HashMap定義

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

從HashMap的定義上,我們可以知道以下幾點(diǎn):

  • HashMap為散列表,用于存儲(chǔ)[key-value]鍵值對(duì)
  • 繼承了AbstractMap,實(shí)現(xiàn)了Map、Cloneable、Serializable
  • 由于Map的設(shè)計(jì)是非同步的,從實(shí)現(xiàn)上看HashMap也是非線程安全的。(線程同步的場景可以使用ConcurrentHashMap)
  • 可以實(shí)現(xiàn)克隆
  • 可以序列化

1.4 一些屬性

    // 初始化容量,必須為2的n次冪(主要是為了后續(xù)計(jì)算index考慮)
    static final int DEFAULT_INITIAL_CAPACITY = 1 << 4; // aka 16
 
    // 最大容量,2的30次冪 
    static final int MAXIMUM_CAPACITY = 1 << 30;

    // 默認(rèn)的加載因子,size=capacity*factor
    static final float DEFAULT_LOAD_FACTOR = 0.75f;

    // 使用紅黑樹的閥值
    // 當(dāng)鏈表中的個(gè)數(shù)大于該值時(shí),會(huì)將鏈表轉(zhuǎn)換為紅黑樹進(jìn)行存儲(chǔ)
    // 該值必須大于2,且最小值為8
    static final int TREEIFY_THRESHOLD = 8;

    // resize時(shí)不使用樹的閥值,必須小于TREEIFY_THRESHOLD
    static final int UNTREEIFY_THRESHOLD = 6;

    // 紅黑樹最小容量
    // 最小值為:4 * TREEIFY_THRESHOLD
    static final int MIN_TREEIFY_CAPACITY = 64;

1.5 重要的Node

// 用于存儲(chǔ)數(shù)據(jù)的節(jié)點(diǎn)
static class Node<K,V> implements Map.Entry<K,V> {
        // 用于定位數(shù)組索引位置
        final int hash;
        // 存儲(chǔ)的key
        final K key;
        // 存儲(chǔ)的value
        V value;
        // 鏈表中下一個(gè)值
        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的一個(gè)靜態(tài)內(nèi)部類,實(shí)現(xiàn)了Map.Entry接口,本質(zhì)是就是一個(gè)鍵值對(duì)。

1.6 構(gòu)造方法

在看構(gòu)造方法前,先來看幾個(gè)關(guān)鍵的屬性:

    // 存儲(chǔ)數(shù)據(jù)的數(shù)據(jù),首次使用時(shí)被初始化,需要時(shí)可以被擴(kuò)容
    // 當(dāng)分配時(shí)它的長度一定是2的n次冪
    transient Node<K,V>[] table;

    // 數(shù)組中實(shí)際存儲(chǔ)的鍵值對(duì)數(shù)量
    transient int size;

    //  用于fail-fast
    transient int modCount;
    // HashMap所能容納的最大數(shù)據(jù)量的Node(鍵值對(duì))個(gè)數(shù)
    // threshold = capacity * load factor
    // 超過該值那么將進(jìn)行擴(kuò)容
    int threshold;

    // 負(fù)載因子
    final float loadFactor;

下面我們來看下HashMap的幾個(gè)構(gòu)造方法:

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

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

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

這些構(gòu)造方法其實(shí)就是對(duì)上面的幾個(gè)屬性進(jìn)行了初始化。

2.原理分析

2.1 確定在Hash數(shù)組中的index

方法一:

static final int hash(Object key) {
    int h;
    return (key == null) ? 0 : (h = key.hashCode()) ^ (h >>> 16);
}
    
方法二:
static int indexFor(int h, int length) {  //jdk1.7的源碼,jdk1.8沒有這個(gè)方法,但是實(shí)現(xiàn)原理一樣的
  return h & (length-1);  //第三步 取模運(yùn)算
}

分析下上面的兩個(gè)算法,我們可以發(fā)現(xiàn)HashMap采用的hash算法主要包括以下三塊內(nèi)容:

  1. 取得key的hashCode值
    在這里我們需要明確下hashCode()方法與equals()方法之間的關(guān)系:
    如果x.equals(y)返回“true”,那么x和y的hashCode()必須相等。
    如果x.equals(y)返回“false”,那么x和y的hashCode()有可能相等,也有可能不等。

  2. 高位運(yùn)算

(h = key.hashCode()) ^ (h >>> 16)

這么做可以在數(shù)組table的length比較小的時(shí)候,也能保證考慮到高低Bit都參與到Hash的計(jì)算中,同時(shí)不會(huì)有太大的開銷。

  1. 取模運(yùn)算
    這個(gè)方法非常巧妙,它通過h&(table.length-1)來得到對(duì)象的保存位置(數(shù)組中的index),因?yàn)閿?shù)組的長度lenth總是為2的n次方,h&(length-1)運(yùn)算等價(jià)于對(duì)length取模,也就是h%length,但是&比%具有更高的效率。

2.2 put方法

上面分析了這么多,這個(gè)章節(jié)才是我們的重點(diǎn),廢話不多說,我們來看put方法到底做了那些神級(jí)操作。

public V put(K key, V value) {
        return putVal(hash(key), key, value, false, true);
    }
    
     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. 如果是首次使用(tab為空),那么進(jìn)行resize操作
        if ((tab = table) == null || (n = tab.length) == 0)
            n = (tab = resize()).length;
            
        //2.根據(jù)hash值獲得數(shù)組index值,判斷table[index]是否為null
        //如果table[index]為null,直接新建node元素。
        if ((p = tab[i = (n - 1) & hash]) == null)
            tab[i] = newNode(hash, key, value, null);
        else {
            Node<K,V> e; K k;
            // 3. 節(jié)點(diǎn)key存在,直接進(jìn)行覆蓋
            if (p.hash == hash &&
                ((k = p.key) == key || (key != null && key.equals(k))))
                e = p;
                
            // 4.如果當(dāng)前table[index]為紅黑樹節(jié)點(diǎn)對(duì)象,存儲(chǔ)節(jié)點(diǎn)到書中
            else if (p instanceof TreeNode)
                e = ((TreeNode<K,V>)p).putTreeVal(this, tab, hash, key, value);
                
            // 5.如果節(jié)點(diǎn)為鏈表    
            else {
                for (int binCount = 0; ; ++binCount) {
                    if ((e = p.next) == null) {
                        p.next = newNode(hash, key, value, null);
                        // 如果鏈表長度大于等于8,則將鏈表轉(zhuǎn)換為紅黑樹
                        if (binCount >= TREEIFY_THRESHOLD - 1) // -1 for 1st
                            treeifyBin(tab, hash);
                        break;
                    }
                    // key已經(jīng)存在直接覆蓋value
                    if (e.hash == hash &&
                        ((k = e.key) == key || (key != null && key.equals(k))))
                        break;
                    p = e;
                }
            }
            
            // tab
            if (e != null) { // existing mapping for key
                V oldValue = e.value;
                if (!onlyIfAbsent || oldValue == null)
                    e.value = value;
                afterNodeAccess(e);
                return oldValue;
            }
        }
        ++modCount;
        // 6.超過最大容量,就進(jìn)行擴(kuò)容
        if (++size > threshold)
            resize();
        afterNodeInsertion(evict);
        return null;
    }

2.3 resize

 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) {
            // 超過最大值就不再進(jìn)行擴(kuò)容了
            if (oldCap >= MAXIMUM_CAPACITY) {
                threshold = Integer.MAX_VALUE;
                return oldTab;
            }
            
            // 沒有超過最大值,就擴(kuò)大為原來的2倍
            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
            // 首次使用時(shí)進(jìn)行的擴(kuò)容
            newCap = DEFAULT_INITIAL_CAPACITY;
            newThr = (int)(DEFAULT_LOAD_FACTOR * DEFAULT_INITIAL_CAPACITY);
        }
        
        // 計(jì)算新的上限
        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;
                
                // 將每個(gè)bucket移動(dòng)到新的bucket
                if ((e = oldTab[j]) != null) {
                    // 將舊的數(shù)組置為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;
                            }
                             // 原索引+oldCap
                            else {
                                if (hiTail == null)
                                    hiHead = e;
                                else
                                    hiTail.next = e;
                                hiTail = e;
                            }
                        } while ((e = next) != null);
                        
                        // 原索引放到bucket里
                        if (loTail != null) {
                            loTail.next = null;
                            newTab[j] = loHead;
                        }
                        
                        // 原索引+oldCap放到bucket里
                        if (hiTail != null) {
                            hiTail.next = null;
                            newTab[j + oldCap] = hiHead;
                        }
                    }
                }
            }
        }
        return newTab;
    }


3. 線程安全性

我們都知道HashMap是非線程安全的,在多線程使用場景中,應(yīng)該盡量避免使用線程不安全的HashMap,而使用線程安全的ConcurrentHashMap。
ConcurrentHashMap使用了分段加鎖的機(jī)制,因此在使用效率上比使用HashTable和Collections.synchronizedMap()更高,而且由于設(shè)計(jì)陳舊,HashTable和Collections.synchronizedMap()正在逐漸退出歷史舞臺(tái)。

4. 結(jié)束語

HashMap在我們?nèi)粘i_發(fā)中,占據(jù)著不可或缺的位置,希望大家能對(duì)其原理有一個(gè)深入的認(rèn)識(shí)和了解。JDK 1.8對(duì)HashMap的優(yōu)化僅僅是冰山一角,讓我們通過HashMap開始擁抱JDK1.8吧。

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

  • HashMap 是 Java 面試必考的知識(shí)點(diǎn),面試官從這個(gè)小知識(shí)點(diǎn)就可以了解我們對(duì) Java 基礎(chǔ)的掌握程度。網(wǎng)...
    野狗子嗷嗷嗷閱讀 6,813評(píng)論 9 107
  • 本文轉(zhuǎn)自 https://zhuanlan.zhihu.com/p/21673805 美團(tuán)點(diǎn)評(píng)技術(shù)團(tuán)隊(duì)· 3 個(gè)月...
    抓兔子的貓閱讀 1,154評(píng)論 0 1
  • Java8張圖 11、字符串不變性 12、equals()方法、hashCode()方法的區(qū)別 13、...
    Miley_MOJIE閱讀 3,906評(píng)論 0 11
  • 0.描述 在一個(gè)返回值為void方法中使用了return。這句話的意思是在一個(gè)并不期望得到返回值的方法中使用了 *...
    SMouse閱讀 403評(píng)論 0 0
  • 坐聽潮起潮落 遠(yuǎn)觀月圓月缺 靜賞花開花謝 歲月如梭 穿行于日月變換間 匆匆再匆匆 行走于人間三月天 嬌美的面龐如花...
    雙魚座cy閱讀 532評(píng)論 8 21

友情鏈接更多精彩內(nèi)容