1. 程式人生 > >HashMap原始碼解析——基於jdk11

HashMap原始碼解析——基於jdk11

HashMap原始碼解析——基於jdk11

插入流程

首先我們從put方法說起:

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

繼續往下看putVal方法:

final V putVal(int hash, K key, V value, boolean onlyIfAbsent,
                   boolean
evict) { //如果table為空就初始化一個table n為table的長度 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 { //如果key已經存在, e = 存在的值 Node<K,V> e; K k; 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) { //正常情況下,把值插入連結串列的最後面 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已經存在, e = 存在的值 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; }

獲取流程

首先看看

    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) {
            //如果連結串列頭就是要找的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;
    }