HashMap解析(1.8版)

Java8 對 HashMap 進行了一些修改,最大的不同就是利用了紅黑樹,所以其由 數組+鏈表+紅黑樹 組成。
在這裏插入圖片描述
瞭解下一些重要的成員變量

	//tab默認容量 16
    static final int DEFAULT_INITIAL_CAPACITY = 1 << 4;
    //tab最大容量
    static final int MAXIMUM_CAPACITY = 1 << 30;
    //默認擴容因子(默認當size大於CAPACITY * DEFAULT_LOAD_FACTOR時,執行擴容)
    static final float DEFAULT_LOAD_FACTOR = 0.75f;
    //當Node鏈表闕值大於等於8時,將會執行轉換樹的方法
    static final int TREEIFY_THRESHOLD = 8;
    //當Node鏈表闕值小於等於6時,樹將會轉爲鏈表
    static final int UNTREEIFY_THRESHOLD = 6;
    //當tab數組長度大於64的時候,纔會真正開始進行鏈表的樹轉換,否則優先執行擴容
    static final int MIN_TREEIFY_CAPACITY = 64;
    //數組,存儲鏈表或者紅黑樹
    transient Node<K,V>[] table;
    

先着重看下hashMap的 hash()方法

//低16位和高16位做了個異或運算,它對hash code的低位添加了隨機性並且混合了高位的部分特徵,顯著減少了碰撞衝突的發生
static final int hash(Object key) {
        int h;
        return (key == null) ? 0 : (h = key.hashCode()) ^ (h >>> 16);
    }
//然後和tab.length-1 做與操作,確定對象在table中的位置
index = (table.length - 1) & 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;
        //第一次執行put,進入resize()擴容
        if ((tab = table) == null || (n = tab.length) == 0)
            n = (tab = resize()).length;
        //在這裏通過計算hash值和table的長度,獲取頭節點Node<K,V> p
        if ((p = tab[i = (n - 1) & hash]) == null)
            //如果該位置爲null,新建一個頭節點
            tab[i] = newNode(hash, key, value, null);
        else {
            Node<K,V> e; K k;
            //通過hash、==、equals方法 發現頭節點就是目標節點
            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;
                    }
                    //發現目標
                    if (e.hash == hash &&
                        ((k = e.key) == key || (key != null && key.equals(k))))
                        break;
                    p = e;
                }
            }
            //如果找到了目標節點,value替換
            if (e != null) { // existing mapping for key
                V oldValue = e.value;
                if (!onlyIfAbsent || oldValue == null)
                    e.value = value;
                afterNodeAccess(e);
                return oldValue;
            }
        }
        ++modCount;
        //這裏需要擴容的闕值threshold在resize方法中會進行計算,方便下次擴容
        if (++size > threshold)
            resize();
        afterNodeInsertion(evict);
        return null;
    }

在瞭解擴容方法之前,先要了解下,擴容之後,是怎麼高效重新計算元素的位置

數組的大小永遠是一個2次冪,在擴容之後,一個元素的新索引要麼是在原位置,要麼就是在原位置加上擴容前的容量。這個方法的巧妙之處全在於&運算,之前提到過&運算只會關注n – 1(n = 數組長度)的有效位,當擴容之後,n的有效位相比之前會多增加一位(n會變成之前的二倍,所以確保數組長度永遠是2次冪很重要),然後只需要判斷hash在新增的有效位的位置是0還是1就可以算出新的索引位置,如果是0,那麼索引沒有發生變化,如果是1,索引就爲原索引加上擴容前的容量。
擴容resize()
圖示:
在這裏插入圖片描述

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;
            }
            //容量直接變爲2倍,擴容闕值也是2倍,如果這是第二次擴容的話,默認情況下
            //newCap = 32,newThr = 24
            else if ((newCap = oldCap << 1) < MAXIMUM_CAPACITY &&
                     oldCap >= DEFAULT_INITIAL_CAPACITY)
                newThr = oldThr << 1; // double threshold
        }
        //oldCap=0,但是oldThr > 0,說明用戶創建HashMap指定了容量
        else if (oldThr > 0)
            newCap = oldThr;
        else {
            //這裏是第一次擴容,初始化默認容量
            newCap = DEFAULT_INITIAL_CAPACITY;
            //計算下次擴容的闕值,0.75 * 16 = 12
            newThr = (int)(DEFAULT_LOAD_FACTOR * DEFAULT_INITIAL_CAPACITY);
        }
        if (newThr == 0) {
            // 如果newThr還沒有被賦值,那麼就根據newCap計算出閾值
            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;
                    //如果只有頭節點,那麼直接根據hash移到新的數組
                    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 {
                        //在這裏分爲倆組鏈表lowNode heightNode
                        //通過hash & oldCap 和舊的容量進行比較
                        //如果爲0則位置不動,如果不爲0,則位置= 原index+oldCap
                        Node<K,V> loHead = null, loTail = null;
                        Node<K,V> hiHead = null, hiTail = null;
                        Node<K,V> next;
                        do {
                            next = e.next;
                            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);
                        if (loTail != null) {
                            loTail.next = null;
                            newTab[j] = loHead;
                        }
                        if (hiTail != null) {
                            hiTail.next = null;
                            newTab[j + oldCap] = hiHead;
                        }
                    }
                }
            }
        }
        return newTab;
    }

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;
        //查詢頭節點Node<K,V> p
        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;
            //頭節點正好是目標節點
            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;
    }

最後來看下get()

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;
        //如果table不爲空、並且根據hash值計算能獲取頭節點
        if ((tab = table) != null && (n = tab.length) > 0 &&
            (first = tab[(n - 1) & hash]) != null) {
            //頭節點就是目標節點
            if (first.hash == hash &&
                ((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;
    }

關於紅黑樹部分,暫時略過,後面會開新的篇章進行講解

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