筆記--HashMap相關


1.HashMap底層實現原理是什麼?
    HashMap由數組+鏈表組成,JDK8中新增了紅黑樹,當鏈表長度達到8(默認閾值)時,鏈表轉化成紅黑樹,鏈表過長對性能有很大的影響。
    //HashMap初始化長度
    static final int DEFAULT_INITIAL_CAPACITY = 1<<4;//位運算,1左移四位是16
    //HashMap最大長度
    static final int MAXIMUM_CAPACITY = 1<<30;//1073741824
    //默認加載因子(擴容因子)
    static final float DEFAULT_LOAD_FACTOR = 0.75f;
    //鏈表轉化成紅黑樹的閾值
    static final int TREEIFY_THRESHOLD = 8;
    //紅黑樹轉化成鏈表的閾值
    static final int UNTREEIFY_THRESHOLD = 6;
    //最小樹容量
    static final int MIN_TREEIFY_CAPACITY = 64;

    PS:HashMap構造時可以指定默認初始大小和負載因子,

    經典面試題:
    1.JDK8中HashMap擴容時做了哪些優化?
        JDK8在hashmap擴容時不再重新計算每個元素的哈希值,而是通過高位運算(e.hash & oldCap)來判定元素是否需要移動。
        例如:
            key1.hash = 10 0000 1010;
            key2.hash = 10 0001 0001;
            oldCap    = 16 0001 0000;(oldCap就是擴容前table.length)
            key1.hash & oldCap的高一位爲0,擴容時元素下標不變;
            key1.hash & oldCap的高一位爲1,擴容時元素下標=原下標+原數組長度。
            PS:與運算,有0則0,全1則1。
        且JDK8新增元素採用的是尾插法(尾部正序插入),而JDK7是頭部插入(頭部倒序插入),JDK8有效的避免了JDK7在擴容時的死循環和數據丟失的問題,但是仍然存在數據覆蓋的問題,這也就是HashMap線程不安全的一部分原因。

    2.加載因子爲什麼是0.75?
        加載因子是來判斷什麼時候進行擴容。
        當加載因子設置比較大時,擴容發生的頻率比較低且佔用的空間會比較小,但這樣的話發生hash衝突的機率就會增大,因此需要更復雜的數據結構去存儲數據,這樣對元素的操作時間增加,運行效率會降低;
        當加載因子設置較小的時候,會發生頻繁的擴容且佔用空間增大,此時hash衝突的可能性就比較小,操作性能會提高

    3.當有哈希衝突時,HashMap是如何查找並確認元素的?
        當哈希衝突時需要通過判斷 key 值是否相等,才能確認此元素是不是我們想要的元素。

    4.HashMap源碼中有哪些重要的方法?
        查詢、新增和數據擴容
        查詢:查詢時先比較key的hashcode然後去比較key值,將對應的value值返回;

        public V get(Object key) {
            Node<K,V> e;
            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) {
                //判斷第一個節點是否是需要的值
                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);
                    //循環,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;
        }

        新增:
        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;
            //如果鏈表爲空則創建鏈表
            if ((tab = table) == null || (n = tab.length) == 0)
                n = (tab = resize()).length;
            //根據key的hash值計算要插入的數組索引i,如果tab[i] == null,則直接插入
            if ((p = tab[i = (n - 1) & hash]) == null)
                tab[i] = newNode(hash, key, value, null);
            else {
                Node<K,V> e; K k;
                //如果key已存在,覆蓋原值
                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 {
                    //鏈表結構訓話插入,放在鏈表的尾部(JDK7是插入鏈表頭部)
                    for (int binCount = 0; ; ++binCount) {
                        if ((e = p.next) == null) {
                            p.next = newNode(hash, key, value, null);
                            if (binCount >= TREEIFY_THRESHOLD - 1)
                                //判斷轉化成紅黑樹還是擴容
                                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;
        }

        final void treeifyBin(Node<K,V>[] tab, int hash) {
    
            int n, index; Node<K,V> e;
            //當整個map中元素個數小於64時,只是進行擴容
            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);
    
            }

        }


    數據擴容:
    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) {
            //如果已經達到最大容量,只將閾值設置成Integer.MAX_VALUES,返回
            if (oldCap >= MAXIMUM_CAPACITY) {
                threshold = Integer.MAX_VALUE;
                return oldTab;
            }
            //如果擴容後newCap未達到最大容量且oldCap大於初始大小16
            //將閾值變爲原來的兩倍
            else if ((newCap = oldCap << 1) < MAXIMUM_CAPACITY &&
                     oldCap >= DEFAULT_INITIAL_CAPACITY)
                newThr = oldThr << 1; 
        }
        //如果oldCap大於代表初始化時用的是HashMap的有參構造
        else if (oldThr > 0)
            newCap = oldThr;
        else {//HashMap的默認構造
            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;
        //判斷原數據不爲空,開始將數據轉移到新table裏面
        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 {
                        //鏈表複製,JDK8擴容優化
                        Node<K,V> loHead = null, loTail = null;
                        Node<K,V> hiHead = null, hiTail = null;
                        Node<K,V> next;
                        do {
                            next = e.next;
                            //&運算,如果高一位爲0,保持原索引
                            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;
    }

    5.Hashmap是如何導致死循環的?
    JDK7爲例
    線程1->put(key(3))
    線程2->put(key(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; //假設線程1執行到這裏,丟失了CPU使用權
                if (rehash) {
                    e.hash = null == e.key ? 0 : hash(e.key);
                }
                int i = indexFor(e.hash, newCapacity);
                e.next = newTable[i];
                newTable[i] = e;
                e = next;
            }
        }
    }

    當線程1執行到”Entry<K,V> next = e.next;“時,此時e = key(3),e.next = key(7),然後此時CPU使用權被線程2奪取,然後線程2重新rehash,鏈表順序被反轉,由key(3)->key(7)變成了key(7)->key(3),此時線程1再次獲取CPU使用權,接着執行代碼,newTalbe[i]=e把key(3)的next設置爲key(7),而下次循環時查詢到key(7)的next元素爲key(3),於是就形成了key(3)和key(7)的循環引用,因此導致了死循環發生。

    6.爲什麼HashMap線程不安全?
    https://blog.csdn.net/swpu_ocean/article/details/88917958
小結:
HashMap併發的情況下本身就不是線程安全的,建議使用ConcurrentHashMap


 

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