Java集合框架1-- HashMap

HashMap的知識點能夠說在面試中常常被問到,是Java中比較常見的一種數據結構。因此這一篇就經過源碼來深刻理解下HashMap。java

1 HashMap的底層是如何實現的?(基於JDK8)

1.1 HashMap的類結構和成員

/**
HashMap繼承AbstractMap,而AbstractMap又實現了Map的接口
*/ 
public class HashMap<K,V> extends AbstractMap<K,V>
    implements Map<K,V>, Cloneable, Serializable

從上面源碼能夠看出HashMap支持序列化和反序列化,並且實現了cloneable接口,能支持clone()方法複製一個對象。node

1.1.1 HashMap源碼中的幾個成員屬性

//最小容量爲16,且必定是2的冪次
static final int DEFAULT_INITIAL_CAPACITY = 1 << 4; // aka 16

 //最大容量爲2的30次方
static final int MAXIMUM_CAPACITY = 1 << 30;

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

//當某節點的鏈表長度大於8而且hash數組的容量達到64時,鏈表將會轉換成紅黑樹
static final int TREEIFY_THRESHOLD = 8;

//當鏈表長度小於6時,紅黑樹將轉換成鏈表
static final int UNTREEIFY_THRESHOLD = 6;

//鏈表變成紅黑樹的最小容量
static final int MIN_TREEIFY_CAPACITY = 64;

從上面的源碼能夠看出,JDK1.8的HashMap其實是由數組+鏈表+紅黑樹組成,在必定條件下鏈表會轉換成紅黑樹。這裏要談一下默認加載因子爲何爲0.75(3/4),加載因子也叫擴容因子,用來判斷HashMap何時進行擴容。選擇0.75的緣由是爲了平衡容量與查找性能:擴容因子越大,形成hash衝突的概率就越大,查找性能就會越低,反之擴容因子越小,所佔容量就會越大。於此同時,負載因子爲3/4的話,和capacity的乘積結果就能夠是一個整數。
面試

下面再看看hash數組中的元素數組

1.1.2 HashMap中的數組節點

​ hash數組通常稱爲哈希桶(bucket),結點在JDK1.7中叫Entry,在JDK1.8中叫Node。安全

//1.8中Node實現entry的接口
static class Node<K,V> implements Map.Entry<K,V> {
    //每一個節點都會包含四個字段:hash、key、value、next
        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; }
    
		//hash值是由key和value的hashcode異或獲得
        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;
            //判斷o對象是否爲Map.Entry的實例
            if (o instanceof Map.Entry) {
                Map.Entry<?,?> e = (Map.Entry<?,?>)o;
                //再判斷二者的key和value值是否相同
                if (Objects.equals(key, e.getKey()) &&
                    Objects.equals(value, e.getValue()))
                    return true;
            }
            return false;
        }
}
//這個是擾動函數,減小hash碰撞
static final int hash(Object key) {
        int h;
    	//將key的高16位與低16位異或(int是2個字節,32位)
        return (key == null) ? 0 : (h = key.hashCode()) ^ (h >>> 16);
    }

1.2 HashMap中的方法

1.2.1 查詢方法

public V get(Object key) {
        Node<K,V> e;
    	//將key值擾動後傳入getNode函數查詢節點
        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 &&
            (first = tab[(n - 1) & hash]) != null) {
            //從第一個節點開始查詢,若是hash值和key值相等,則查詢成功,返回該節點
            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;
}

1.2.2 新增方法

向哈希表中插入一個節點數據結構

public V put(K key, V value) {
    	//將擾動的hash值傳入,調用putVal函數
        return putVal(hash(key), key, value, false, true);
    }
//當參數onlyIfAbsent爲true時,不會覆蓋相同key的值value;當evict是false時,表示是在初始化時調用
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;
        //若是與該節點的hash值和key值都相等,將節點引用賦給e
        if (p.hash == hash &&
            ((k = p.key) == key || (key != null && key.equals(k))))
            e = p;
        //若是p是樹節點的實例,調用紅黑樹方法新增一個樹節點e
        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);
                    //若插入節點後,鏈表節點數大於轉變成紅黑樹的臨界值(>=8)
                    if (binCount >= TREEIFY_THRESHOLD - 1) // -1 for 1st
                        //將鏈表轉換成紅黑樹
                        treeifyBin(tab, hash);
                    break;
                }
                //遍歷過程當中發現了key和hash值相同的節點,用e覆蓋該節點
                if (e.hash == hash &&
                    ((k = e.key) == key || (key != null && key.equals(k))))
                    break;
                p = e;
            }
        }
        //對e節點進行處理
        if (e != null) { 
            V oldValue = e.value;
            if (!onlyIfAbsent || oldValue == null)
                e.value = value;
            afterNodeAccess(e);
            return oldValue;
        }
    }
    //節點插入成功,修改modCount值
    ++modCount;
    //若是達到擴容條件,直接擴容
    if (++size > threshold)
        resize();
    
    afterNodeInsertion(evict);
    return null;
}

1.2.3 擴容方法(很是重要)

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
        newCap = oldThr;
    //數組爲空,且沒有初始化
    else {               // zero initial threshold signifies using defaults
        //初始化數組
        newCap = DEFAULT_INITIAL_CAPACITY;
        newThr = (int)(DEFAULT_LOAD_FACTOR * DEFAULT_INITIAL_CAPACITY);
    }
    //數組爲空,且新的閾值爲0
    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) {
                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
                    //定義現有數組的位置low,擴容後的位置high;high = low + oldCap
                    Node<K,V> loHead = null, loTail = null;
                    Node<K,V> hiHead = null, hiTail = null;
                    Node<K,V> next;
                    do {
                        next = e.next;
                        /*經過(e.hash & oldCap)來肯定元素是否須要移動,
                          e.hash & oldCap大於0,說明位置須要做相應的調整。
                          反之等於0時說明在該容量範圍內,下標位置不變。
                        */
                        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;
                    }
                    //處於高位位置要改變爲j + oldCap
                    if (hiTail != null) {
                        hiTail.next = null;
                        newTab[j + oldCap] = hiHead;
                    }
                }
            }
        }
    }
    return newTab;
}

​ HashMap其實是線程不安全的,在JDK1.7中,鏈表的插入方式爲頭插法,在多線程下插入可能會致使死循環。所以在JDK1.8中替換成尾插法(其實想要線程安全大可用ConcurrentHashMap、Hashtable)多線程

//JDK1.7源碼
void transfer(Entry[] newTable boolean rehash) {
    int newCapacity = newTable.length;
    for (Entry<K,V> e : table) {
        while(null != e) {
            //多線程在這裏會致使指向成環
            Entry<K,V> next = e.next;
            if(rehash) {
                e.hash = null == e.key ? 0 : hash(e.key);
            }
            int i = indexFor(e.hash, new Capacity);
            e.next = newTable[i];
            newTable[i] = e;
            e = next;
        }
    }
}

假如HashMap的容量爲2,其中在數組中有一個元素a(此時已經到達擴容的臨界點)。建立兩個線程t一、t2分別插入b、c,由於沒有鎖,兩個線程都進行到擴容這一步,那麼其中有節點位子由於擴容必然會發生變化(之前的容量不夠),這個時候假設t1線程成功運行,插入成功。可是因爲t2線程的合併,加上節點位置的挪動,就會形成鏈表成環。最後讀取失敗函數

1.2.4 刪除方法

//經過key值刪除該節點,並返回value
public V remove(Object key) {
    Node<K,V> e;
    return (e = removeNode(hash(key), key, null, false, true)) == null ? null : e.value;
}
//刪除某個節點
//若matchValue爲true時,須要key和value都要相等才能刪除;若movable爲false時,刪除節點時不移動其餘節點
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爲刪除點
        Node<K,V> node = null, e; K k; V v;
        //查到頭節點爲所要刪除的點,直接賦於node
        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);
            }
        }
        //對取回的node節點進行處理,當matchValue爲false,或者value相等時
        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
            ++modCount;
            --size;
            afterNodeRemoval(node);
            return node;
        }
    }
    return null;
}

2.一些面試題

2.1 JDK1.8 HashMap擴容時作了哪些優化

  1. 新元素下標方面,1.8經過高位運算(e.hash & oldCap) == 0分類處理表中的元素:低位不變,高位原下標+原數組長度;而不是像1.7中計算每個元素下標。工具

  2. 在resize()函數中,1.8將1.7中的頭插逆序變成尾插順序。可是仍然建議在多線程下不要用HashMap。性能

2.2 HashMap與Hashtable的區別

  1. 線程安全:Hashtable是線程安全的,不容許key,value爲null。
  2. 繼承父類:Hashtable是Dictionary類的子類(Dictionary類已經被廢棄),二者都實現了Map接口。
  3. 擴容:Hashtable默認容量爲11,擴容爲原來的容量2倍+1,因此Hashtable獲取下標直接用模運算符%。
  4. 存儲方式:Hashtable中出現衝突後,只有用鏈表方式存儲。

2.3 HashMap線程不安全,那麼有哪些Map能夠實現線程安全

  1. Hashtable: 直接在方法上加synchronized關鍵字,鎖住整個哈希桶
  2. ConcurrentHashMap:使用分段鎖,相比於Hashtable性能更高
  3. Collectons.synchronizedMap:是使用Collections集合工具的內部類,經過傳入Map封裝一個SynchronizedMap對象,內部定義一個對象鎖,方法經過對象鎖實現。

參考博文:

HashMap 底層實現原理是什麼?JDK8 作了哪些優化?

一個HashMap跟面試官扯了半個小時

相關文章
相關標籤/搜索