天天看點

HashMap主要方法源碼分析主要方法源碼解讀

HashMap源碼分析

  • 主要方法源碼解讀
    • put方法
    • resize方法
    • get方法
    • Hash方法

主要方法源碼解讀

put方法

下面展示一些

内聯代碼片

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;
    //确認table是否為空或者table的長度是否為0(隻有在第一次put的時候才會初始化數組)
    if ((tab = table) == null || (n = tab.length) == 0)
        n = (tab = resize()).length;
    //p = tab[i = (n - 1) & hash] 這塊兒判斷是否有hash沖突,沒有的話直接建立新的node
    if ((p = tab[i = (n - 1) & hash]) == null)
        tab[i] = newNode(hash, key, value, null);
    else {
        Node<K,V> e; K k;
        //判斷是否是重複資料插入,将重複e設定為重複Node
        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 {
        	//将hash沖突的元素下挂至連結清單
            for (int binCount = 0; ; ++binCount) {
                if ((e = p.next) == null) {
                    p.next = newNode(hash, key, value, null);
                    //如果該連結清單長度大于等于7,調用 treeifyBin(tab, hash)  方法去将連結清單轉換成紅黑樹  
                    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;
            }
        }
        if (e != null) { // existing mapping for key
            V oldValue = e.value;
            //如果key已經存在或之前的value為空,更新value的值,傳回老value的值
            if (!onlyIfAbsent || oldValue == null)
                e.value = value;
            afterNodeAccess(e);
            return oldValue;
        }
    }
    ++modCount;
    //modCount++,++size如果超過了數組長度*擴容因子,進行擴容
    if (++size > threshold)
        resize();
    afterNodeInsertion(evict);
    return null;
}
    
           

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) {
    	//如果舊數組的長度超過了2^30,直接将擴容觸發長度增加至Integer.MAX_VALUE,傳回舊數組
        if (oldCap >= MAXIMUM_CAPACITY) {
            threshold = Integer.MAX_VALUE;
            return oldTab;
        }
    	//設定新數組的長度為舊數組的2倍,如果舊數組的長度*2小于2^30且大于預設長度16,新數組的擴容觸發長度設定為舊數組擴容觸發長度的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
        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;
    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
                    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判斷是否将原下标的連結清單分割
                        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);
                    //将e.hash & oldCap == 0的連結清單放在原下标下
                    if (loTail != null) {
                        loTail.next = null;
                        newTab[j] = loHead;
                    }
                    //将e.hash & oldCap != 0的連結清單放在(原下标+舊數組元素長度)
                    if (hiTail != null) {
                        hiTail.next = null;
                        newTab[j + oldCap] = hiHead;
                    }
                }
            }
        }
    }
    return newTab;
}
           

get方法

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);
            do {
                if (e.hash == hash &&
                    ((k = e.key) == key || (key != null && key.equals(k))))
                    return e;
            } while ((e = e.next) != null);
        }
    }
    return null;
}
           

感覺get方法沒啥可看的,都是流水的代碼,唯一覺得NB的就是(n - 1) & hash直接定位了元素下标

Hash方法

static final int hash(Object key) {
    int h;
    return (key == null) ? 0 : (h = key.hashCode()) ^ (h >>> 16);
}
           

這塊兒我是看這個部落客的了解了下标定位的部分

https://blog.csdn.net/weixin_42340670/article/details/80574965

稍微有點流水賬,我也隻是捋了捋邏輯,很多方法還沒有深入

建議自己設計一個類繼承Object類,然後重寫HashCode方法,試着debug進去自己跟着源碼走一遍,會清晰很多

繼續閱讀