1. 程式人生 > >HashMap-陣列+連結串列集合

HashMap-陣列+連結串列集合

field

常量

    //預設初始化容量,最好為2的冪
    static final int DEFAULT_INITIAL_CAPACITY = 1 << 4; // aka 16
    //最大容量
    static final int MAXIMUM_CAPACITY = 1 << 30;
    //預設載入因子
    static final float DEFAULT_LOAD_FACTOR = 0.75f;
    //由雜湊衝突的連結串列結構轉為平衡二叉樹結構節點數閾值(桶的數量需要大於MIN_TREEIFY_CAPACITY )
    static
final int TREEIFY_THRESHOLD = 8; //恢復為連結串列的閾值 static final int UNTREEIFY_THRESHOLD = 6; //TREEIFY_THRESHOLD 對應需要的桶數量 static final int MIN_TREEIFY_CAPACITY = 64;

變數

    //hash節點陣列
    transient Node<K,V>[] table;
    //元素節點
    transient Set<Map.Entry<K,V>> entrySet;
    //大小
transient int size; //運算元 transient int modCount; //擴容臨界值 int threshold; //載入因子 final float loadFactor;

method

tableSizeFor

//相當機智的演算法,用來固定容量為2的倍數
 static final int tableSizeFor(int cap) {  //10000
        int n = cap - 1;   //可能初始化就為2的倍數,則減去1   1111
        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; }

hash

//高16位於hashcode的低16位 異或取值,保證高16位和低16位的變化同時影響hash值
static final int hash(Object key) {
        int h;
        return (key == null) ? 0 : (h = key.hashCode()) ^ (h >>> 16);
    }

resize

//擴容操作,將舊hash表資料移到新的hash表
 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);
        }
        //計算新的threshold
        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;
        //將舊hash表移到新的hash表
        if (oldTab != null) {
            for (int j = 0; j < oldCap; ++j) {
                Node<K,V> e;
                //如果當前舊節點不為空的情況下
                if ((e = oldTab[j]) != null) {
                    oldTab[j] = null;
                    //如果該節點沒有hash衝突,是單節點
                    if (e.next == null)
                        //直接將hash值與桶的容量與運算求桶的索引位。
                        newTab[e.hash & (newCap - 1)] = e;
                    else if (e instanceof TreeNode)
                        //如果e是平衡樹節點,則新增到平衡樹中
                        ((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 或 oldCap(2的冪,這是必然的)
                               //這是hash本來就小於oldCap的情況
                            if ((e.hash & oldCap) == 0) {
                                //將剩下的節點逐個copy
                                if (loTail == null)
                                    loHead = e;
                                else
                                    loTail.next = e;
                                loTail = e;
                            }
                            //這是hash本來就大於oldCap的情況
                            else {
                                //將剩下的節點逐個copy
                                if (hiTail == null)
                                    hiHead = e;
                                else
                                    hiTail.next = e;
                                hiTail = e;
                            }
                            //多執行緒條件下可能反正死迴圈
                            //迴圈列表
                        } while ((e = next) != null);
                        //小於oldCap的索引,如果有節點資料,則保持不變
                        if (loTail != null) {
                            loTail.next = null;
                            newTab[j] = loHead;
                        }
                        //大於oldCap的索引則,如果有節點資料,在原基礎上加上oldCap
                        if (hiTail != null) {
                            hiTail.next = null;
                            newTab[j + oldCap] = hiHead;
                        }
                    }
                }
            }
        }
        return newTab;
    }

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;
        //如果tab為空或者長度為0,則初始化
        if ((tab = table) == null || (n = tab.length) == 0)
            n = (tab = resize()).length;
         //如果桶中計算出的索引無hash衝突,則直接新增
        if ((p = tab[i = (n - 1) & hash]) == null)
            tab[i] = newNode(hash, key, value, null);
        else {
        //具有hash衝突
            Node<K,V> e; K k;
            //如果hash值,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 {
                for (int binCount = 0; ; ++binCount) {
                    //如果p的下一個元素為null,則將元素新增到P後
                    if ((e = p.next) == null) {
                        p.next = newNode(hash, key, value, null);
                        //到達節點數閾值,則轉變為紅黑樹
                        if (binCount >= TREEIFY_THRESHOLD - 1) // -1 for 1st
                            treeifyBin(tab, hash);
                        break;
                    }
                    //如果有重複key,則覆蓋
                    if (e.hash == hash &&
                        ((k = e.key) == key || (key != null && key.equals(k))))
                        break;
                    p = e;
                }
            }
            //e 不為null ,則表示已存在相同的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;
    }

getNode

final Node<K,V> getNode(int hash, Object key) {
        Node<K,V>[] tab; Node<K,V> first, e; int n; K k;
        //check 是否含有該元素
        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);
                    //迴圈連結串列
                do {
                    if (e.hash == hash &&
                        ((k = e.key) == key || (key != null && key.equals(k))))
                        return e;
                } while ((e = e.next) != null);
            }
        }
        return null;
    }