jdk源碼解析二之HashMap

HashMap

HashMap的loadFactor爲什麼是0.75?
主要涉及到泊松分佈的概念,猝!!!

一個bucket空和非空的概率爲0.5,通過牛頓二項式等數學計算,得到這個loadfactor的值爲log(2),約等於0.693. 同回答者所說,可能小於0.75 大於等於log(2)的factor都能提供更好的性能,0.75這個數說不定是 pulled out of a hat。

put

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

    static final int hash(Object key) {
        int h;
        //當key爲null,默認存在0索引線性表
        //(因爲hashCode是一個int類型的變量,是4字節,32位,所以這裏會將hashCode的低16位與高16位進行一個異或運算,來保留高位的特徵,以便於得到的hash值更加均勻分佈)
        return (key == null) ? 0 : (h = key.hashCode()) ^ (h >>> 16);
    }

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;
            //如果key相等,且不爲null
            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 {
                //鏈表處理
                //先存A,在存B,接着存C,則數組存的是A,A.next=B,B.next=C,C.next=null
                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;
                    }
                    if (e.hash == hash &&
                            ((k = e.key) == key || (key != null && key.equals(k))))
                        break;
                    p = e;
                }
            }
            //更新key的值
            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;
    }


remove

    public V remove(Object key) {
        Node<K, V> e;
        return (e = removeNode(hash(key), key, null, false, true)) == null ?
                null : e.value;
    }

  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;
            //第一個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);
                }
            }
            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;
    }

replace

    @Override
    public V replace(K key, V value) {
        Node<K, V> e;
        if ((e = getNode(hash(key), key)) != null) {
            V oldValue = e.value;
            e.value = value;
            afterNodeAccess(e);
            return oldValue;
        }
        return null;
    }

 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 &&
                //根據hash映射數組
                (first = tab[(n - 1) & hash]) != null) {
            //如果是first,則直接返回
            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;
    }

get

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

擴容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) {
            if (oldCap >= MAXIMUM_CAPACITY) {
                threshold = Integer.MAX_VALUE;
                return oldTab;
            } else if ((newCap = oldCap << 1) < MAXIMUM_CAPACITY &&
                    oldCap >= DEFAULT_INITIAL_CAPACITY)
                //如果擴容後的大小<MAXIMUM_CAPACITY且不是第一次初始化容量,則擴充一倍Thr
                newThr = oldThr << 1; // double threshold
        } else if (oldThr > 0) // initial capacity was placed in threshold
            newCap = oldThr;
        else {               // zero initial threshold signifies using defaults
            //默認16容量
            newCap = DEFAULT_INITIAL_CAPACITY;
            //默認12,超過12限制容量,則重新擴容
            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爲空
        table = newTab;

        //以下執行擴容操作
        if (oldTab != null) {
            for (int j = 0; j < oldCap; ++j) {
                Node<K, V> e;
                if ((e = oldTab[j]) != null) {
                    //提前釋放GC
                    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;
                            //注意,此種情況爲0,說明hash<當前容量,哪怕擴容後,進行&操作也是一樣的索引值
                            //擴容後,按照之前的數組索引原位保存就行了
                            //尾部插入
                            if ((e.hash & oldCap) == 0) {
                                if (loTail == null)
                                    loHead = e;
                                else
                                    loTail.next = e;
                                loTail = e;
                            } else {
                                //這種情況,說明擴容後的hasn進行&操作時,索引落在擴容的那一半部分
                                if (hiTail == null)
                                    hiHead = e;
                                else
                                    hiTail.next = e;
                                hiTail = e;
                            }
                        } while ((e = next) != null);
                        //爲什麼擴容後,相同的在原位置保存,而不同的則當前索引+之前原位置索引保存?
                        //因爲這裏的擴容都是擴容一倍,也就是01000擴容後變成10000
                        // 當e.hash & oldCap == 0,說明hash<當前容量,也就是落在0~1000範圍內,哪怕擴容後,進行&操作也是一樣的索引值
                        //!=0,則說明第一e.hash落在0~1000範圍內,第二包含1000這個位置.而1000是之前擴容前的容量,所以最新的地址爲擴容前容量+當前索引
                        //原位置保存
                        if (loTail != null) {
                            loTail.next = null;
                            newTab[j] = loHead;
                        }
                        //存儲索引在擴容的那部分
                        if (hiTail != null) {
                            hiTail.next = null;
                            newTab[j + oldCap] = hiHead;
                        }
                    }
                }
            }
        }
        return newTab;
    }

迭代器

        final Node<K, V> nextNode() {
            Node<K, V>[] t;
            Node<K, V> e = next;
            if (modCount != expectedModCount)
                throw new ConcurrentModificationException();
            if (e == null)
                throw new NoSuchElementException();
            //遍歷當前entry的下一個節點,如果沒有則遍歷數組,查找下一個鏈表節點
            if ((next = (current = e).next) == null && (t = table) != null) {
                do {
                } while (index < t.length && (next = t[index++]) == null);
            }
            return e;
        }

總結

JDK8中,改變了底層數據結構,爲線性表+鏈表+紅黑樹
產生hash值碰撞後,用鏈表存儲碰撞的值

什麼時候採用紅黑樹?

當桶裏面存的鏈表個數>8,同時數組長度>64,的時候採用紅黑樹
在這裏插入圖片描述
在這裏插入圖片描述
默認加載因子0.75
在這裏插入圖片描述
默認容量16,加載擴容的大小12
在這裏插入圖片描述
key一樣時,覆蓋舊的value
可以存null,索引0

爲什麼每次擴容後,是2的冪次方?

是因爲在使用2的冪的數字的時候,Length-1的值是所有二進制位全爲1,這種情況下,index的結果等同於HashCode後幾位的值。
只要輸入的HashCode本身分佈均勻,Hash算法的結果就是均勻的。
這是爲了實現均勻分佈。

在這裏插入圖片描述

爲什麼擴容後,相同的在原位置保存,而不同的則當前索引+之前原位置索引保存?

//因爲這裏的擴容都是擴容一倍,也就是01000擴容後變成10000
// 當e.hash & oldCap == 0,說明hash<當前容量,也就是落在0~1000範圍內,哪怕擴容後,進行&操作也是一樣的索引值
//!=0,則說明第一e.hash落在0~1000範圍內,第二包含1000這個位置.而1000是之前擴容前的容量,所以最新的地址爲擴容前容量+當前索引
                        //原位置保存
                        if (loTail != null) {
                            loTail.next = null;
                            newTab[j] = loHead;
                        }
                        //存儲索引在擴容的那部分
                        if (hiTail != null) {
                            hiTail.next = null;
                            newTab[j + oldCap] = hiHead;
                        }

爲啥用尾插法?

jdk7因爲頭插法存在環形問題
而jdk8,使用尾插,在擴容時會保持鏈表元素原本的順序,就不會出現鏈表成環的問題了

爲什麼線程不安全?

在這裏插入圖片描述
在jdk1.7中,在多線程環境下,擴容時會造成環形鏈或數據丟失。

在jdk1.8中,在多線程環境下,會發生數據覆蓋的情況。

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