JDK8HashMap源碼

進入這篇文章之前,我想清楚的說一說怎麼去理解HashMap源碼。它先是使用的hash算法,那麼哈希算法需要注意的那就是怎麼hash,怎麼減少衝突,怎麼避免衝突。然後是Map,Map是存儲這些<K,V>結構Entity,那麼HashMap需要注意的就是HashMap的初始化過程,什麼時候進行數組(桶)擴容等等

構造和初始化

要深入瞭解HashMap就必須先了解它的這幾個比較重要屬性

    
    //節點,就是Entity
    transient Node<K,V>[] table;
    //同來記錄使用過的那些鍵值對
    transient Set<Map.Entry<K,V>> entrySet;

    //Map中k,v的對數
    transient int size;
    //threshold(threshold=capacity*loadFactor)是一個閾值,是觸發resize的一個重要條件
    int threshold;
    //負載因子
    final float loadFactor;

HashMap有四種構造方法,如下代碼

/*
自定義初始容量和負載因子
代碼解釋:
先進行判斷傳進來的初始容量是否合法,如果初始化容量超出了最大容量範圍,就將給它設置最大容量的值
再判斷負載因子是否合法,如果是合法的就將次負載因子正確的初始化。  threshold(threshold=capacity*loadFactor)是一個閾值,當HashMap的size大於這個閾值,就會進行 resize
*/
    //默認初始容量16  
    static final int DEFAULT_INITIAL_CAPACITY = 1 << 4; // aka 16
   
    //最大容量是1<<30
    static final int MAXIMUM_CAPACITY = 1 << 30;
   
    //默認的負載因子
    static final float DEFAULT_LOAD_FACTOR = 0.75f;

    //樹形化的閾值
    static final int TREEIFY_THRESHOLD = 8;

    //在剪枝的時候取消樹形化的閾值
    static final int UNTREEIFY_THRESHOLD = 6;

    //最小樹形化容量	
    static final int MIN_TREEIFY_CAPACITY = 64;


public HashMap(int initialCapacity, float loadFactor) {
        if (initialCapacity < 0)
            throw new IllegalArgumentException("Illegal initial capacity: " +
                                               initialCapacity);
        if (initialCapacity > MAXIMUM_CAPACITY)
            initialCapacity = MAXIMUM_CAPACITY;
        if (loadFactor <= 0 || Float.isNaN(loadFactor))
            throw new IllegalArgumentException("Illegal load factor: " +
                                               loadFactor);
        this.loadFactor = loadFactor;
        //tabelSizeFor(int cap)方法是爲了對於一些不是2的冪次方的數求出大於initialCapacity的最小的2的冪次方數,然後賦值給threshold。值得注意的是,我看了看JDK8以前的代碼,這塊是沒有這個tableSizeFor操作,而是直接將initialCapacity賦值給threshold。
        this.threshold = tableSizeFor(initialCapacity);
    }

  
    public HashMap(int initialCapacity) {
        this(initialCapacity, DEFAULT_LOAD_FACTOR);
    }

    /**
    默認容量16,負載因子0.75
     */
    public HashMap() {
        this.loadFactor = DEFAULT_LOAD_FACTOR; // all other fields defaulted
    }


    public HashMap(Map<? extends K, ? extends V> m) {
        this.loadFactor = DEFAULT_LOAD_FACTOR;
        putMapEntries(m, false);
    }

對於上面說到過的tableSizeFor方法,可以來看看是怎麼實現的,很精緻的一段代碼

     /*
     提出問題:
     1.爲什麼cap-1
     2.爲什麼要用五個移位或操作
     */
     /*
     解決問題:
     先說第二個問題
     以5爲例,我們都知道一個int值是4個字節,也就是32爲
     0101
     0010 -> 0111
             0000 -> 0111 
             .....
             移位或的結果是0111(32爲數前面的0此處省略)
             
      因此我們可以看出來這些移位或運算都是爲了使得最小的大於這個數的2的冪次方這個數的後面所有位都變爲1,然後我們在n在合理範圍內+1就可以得到我們想要得到的值了。
      
      現在來說第一個問題,爲什麼是cap-1呢。我們可以試圖想一想,如果輸入這個值本來就是2的冪次方,那麼這麼一系列操作之後我們會驚奇的發現,求出來的值會是我們想要求出的值的2倍。這就是爲什麼先對cap-1
      
     */
     static final int tableSizeFor(int cap) {
        int n = cap - 1;
        n |= n >>> 1;
        n |= n >>> 2;
        n |= n >>> 4;
        n |= n >>> 8;
        n |= n >>> 16;
        //如果n<0,就返回1,n>=0,如果n>=最大容量,就返回最大容量,否則就返回n+1
        return (n < 0) ? 1 : (n >= MAXIMUM_CAPACITY) ? MAXIMUM_CAPACITY : n + 1;
    }

        /*輸出
        tableSizeFor(5)=8
        tableSizeFor(8)=8
        tableSizeFor(9)=16
        */

測試

    public static void main(String[] args) {
        System.out.println("tableSizeFor(5)="+tableSizeFor(5));
        System.out.println("tableSizeFor(8)="+tableSizeFor(8));
        System.out.println("tableSizeFor(9)="+tableSizeFor(9));
    }
    static final int MAXIMUM_CAPACITY = 1 << 30;
    static final int tableSizeFor(int n) {
        int n = cap - 1;
        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;
    }


正常情況
tableSizeFor(5)=8
tableSizeFor(8)=8
tableSizeFor(9)=16

註釋掉cap-1並進行相應替換後的情況
tableSizeFor(5)=8
tableSizeFor(8)=16
tableSizeFor(9)=16

put方法

說put前,肯定要先說說hash方法,在1.8中的hash和1.7中不同,比1.7中右移變少(也就是位擾動),有一部分是因爲在1.8中加入了紅黑樹在同一index下,保證了查找效率,不會因爲散列集中引起性能大幅度下降。

    
   static final int hash(Object key) {
        int h;
        return (key == null) ? 0 : (h = key.hashCode()) ^ (h >>> 16);
   } 
 
   public V put(K key, V value) {
        return putVal(hash(key), key, value, false, true);
    }

    //hash就是hash(k),onlyIfAbsent如果是true的話,就是如果key相同的話不進行覆蓋,evict如果是false的話就表示初始化
    final V putVal(int hash, K key, V value, boolean onlyIfAbsent,
                   boolean evict) {
        Node<K,V>[] tab; Node<K,V> p; int n, i;
        //1.判斷當前hashtable是否爲空,如果爲空就進行初始化 resize方法既能用於初始化,又能用於擴容
        if ((tab = table) == null || (n = tab.length) == 0)
            n = (tab = resize()).length;
        //2.根據(n-1)&hash得到index,判斷index的位置是否爲空(鏈表頭或樹根),如果是空就new一個Node並放到這個位置
        if ((p = tab[i = (n - 1) & hash]) == null)
            tab[i] = newNode(hash, key, value, null);
        //3.如果index這個位置不爲空
        else {
            Node<K,V> e; K k;
            //p就是當前index下對應的Node節點
            //3-1.(如果當前桶放的是鏈表)如果p的key對應的值和準備要方進來的key的值是相同的,就把這個值(OldNode)記下來(記爲e)
            if (p.hash == hash &&
                ((k = p.key) == key || (key != null && key.equals(k))))
                e = p;
            //3-2.(如果當前桶放的是樹)如果是樹節點,就調用putTreeVal,在下面會說
            else if (p instanceof TreeNode)
                e = ((TreeNode<K,V>)p).putTreeVal(this, tab, hash, key, value);
            //3-3.如果不是覆蓋操作,那就進行遍歷鏈表(因爲在3-2中已經排除了是樹),找到鏈表最後的一個節點進行尾插,並用binCount記錄當前正在遍歷的鏈表此刻的長度。
            else {
                for (int binCount = 0; ; ++binCount) {
                    if ((e = p.next) == null) {
                        //到達鏈表尾部的話就進行尾插
                        p.next = newNode(hash, key, value, null);
                        //如果binCount=7(TREEIFY_THRESHOLD-1)就說已經達到樹形化的一個條件了(另一個條件是table.length>=MIN_TREEIFY_CAPACITY,默認爲64),因爲現在未加入新節點都已經是7了,因此肯定是會到達樹化的閾值,因此會進入treeifyBin(tab, hash)方法。
                        if (binCount >= TREEIFY_THRESHOLD - 1) 
                            treeifyBin(tab, hash);
                        break;
                    }
                    //如果未到達尾部,就對hash值進行比對,如果hash值相同並且key也是相同的,那就說明找到要替換的節點(就可以break了)
                    if (e.hash == hash &&
                        ((k = e.key) == key || (key != null && key.equals(k))))
                        break;
                    
                    //沒找到要替換的節點就替換以便於通過p訪問下一個Node(循環要素)
                    p = e;
                }
            }
            
            //如果e!=null就說明有需要替換的值(如果遍歷到鏈表尾部,e=null)
            if (e != null) { 
                //oldValue拿出來準備返回
                V oldValue = e.value;
                //onlyIfAbsent默認false(有相同就替換)或者以前的值是null就進行替換
                if (!onlyIfAbsent || oldValue == null)
                    e.value = value;
                //空方法
                afterNodeAccess(e);
                //返回被替換的值
                return oldValue;
            }
        }
        
        //如果能執行到此處的話,說明是添加了一個節點而不是修改了一個節點,因此++modCount
        ++modCount;
        //對size值進行++操作,如果size>threshold,就要進行擴容
        if (++size > threshold)
            resize();
        //空方法
        afterNodeInsertion(evict);
        //不是更新進返回null
        return null;
    }
   
   //new一個Node節點
   Node<K,V> newNode(int hash, K key, V value, Node<K,V> next) {
        return new Node<>(hash, key, value, next);
    }
   //沒有任何東西,這些空方法並且是afterxx都可作爲回調方法
   void afterNodeAccess(Node<K,V> p) { }
   void afterNodeInsertion(boolean evict) { }
//給紅黑樹裏添加Node
final TreeNode<K,V> putTreeVal(HashMap<K,V> map, Node<K,V>[] tab,
                                       int h, K k, V v) {
            Class<?> kc = null;
            boolean searched = false;
            //取樹根,如果當前Node的parent!=null,說明不是根,需要循環找根。如果parent==null說明就是根
            TreeNode<K,V> root = (parent != null) ? root() : this;
            //從根開始遍歷這棵樹
            for (TreeNode<K,V> p = root;;) {
                int dir, ph; K pk;
                //根據哈希判斷去左還是去右
                if ((ph = p.hash) > h)
                    dir = -1;
                else if (ph < h)
                    dir = 1;
                //如果key相等就返回p,說明找到替換的節點了
                else if ((pk = p.key) == k || (k != null && k.equals(pk)))
                    return p;
                //如果hash相等,但是key不相等
                else if ((kc == null &&
                          (kc = comparableClassFor(k)) == null) ||
                         (dir = compareComparables(kc, k, pk)) == 0) {
                    if (!searched) {
                        TreeNode<K,V> q, ch;
                        searched = true;
                        //如果從當前hash相同的節點的子樹中找到key相同的就返回
                        if (((ch = p.left) != null &&
                             (q = ch.find(h, k, kc)) != null) ||
                            ((ch = p.right) != null &&
                             (q = ch.find(h, k, kc)) != null))
                            return q;
                    }
                    //當哈希值相同並且不可比較
                    dir = tieBreakOrder(k, pk);
                }
                
                //如果hash不相等,根據上邊的dir進行選路
                TreeNode<K,V> xp = p;
                if ((p = (dir <= 0) ? p.left : p.right) == null) {
                    Node<K,V> xpn = xp.next;
                    TreeNode<K,V> x = map.newTreeNode(h, k, v, xpn);
                    if (dir <= 0)
                        xp.left = x;
                    else
                        xp.right = x;
                    xp.next = x;
                    x.parent = x.prev = xp;
                    if (xpn != null)
                        ((TreeNode<K,V>)xpn).prev = x;
                    
                    //插入後並且進行樹的平衡
                    moveRootToFront(tab, balanceInsertion(root, x));
                    return null;
                }
            }
        }
//循環找根
final TreeNode<K,V> root() {
            for (TreeNode<K,V> r = this, p;;) {
                if ((p = r.parent) == null)
                    return r;
                r = p;
            }
        }


 //如果table==null就進行初始化,table.length<MIN_TREEIFY_CAPACITY=64,就進行桶的擴容而不是進行樹化
 final void treeifyBin(Node<K,V>[] tab, int hash) {
        int n, index; Node<K,V> e;
        if (tab == null || (n = tab.length) < MIN_TREEIFY_CAPACITY)
            resize();
        //如果滿足上面集合條件就遍歷並進行樹化
        else if ((e = tab[index = (n - 1) & hash]) != null) {
            TreeNode<K,V> hd = null, tl = null;
            do {
                TreeNode<K,V> p = replacementTreeNode(e, null);
                if (tl == null)
                    hd = p;
                else {
                    p.prev = tl;
                    tl.next = p;
                }
                tl = p;
            } while ((e = e.next) != null);
            if ((tab[index] = hd) != null)
                hd.treeify(tab);
        }
    }

get方法

    
    //通過key進行查找
    public V get(Object key) {
        Node<K,V> e;
        //在傳入getNode方法時先對key進行hash
        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!=null,並且hash對應的桶的位置也要有值
        if ((tab = table) != null && (n = tab.length) > 0 &&
            (first = tab[(n - 1) & hash]) != null) {
            //如果key可以被直接找到就返回
            if (first.hash == hash && ((k = first.key) == key || (key != null && key.equals(k))))
                return first;
            //如果first存在next
            if ((e = first.next) != null) {
                //如果是樹型,就調用getTreeNode去找
                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);
            }
        }
        //找不到就返回null
        return null;
    }


remove方法

    
    //根據key移除
    public V remove(Object key) {
        Node<K,V> e;
        //傳入hash,key,value=null,machValue=false,movable=true
        return (e = removeNode(hash(key), key, null, false, true)) == null ?
            null : e.value;
    }

    //如果matchable=true,就表示表示只有key,value同時相等時才刪除   movale如果爲false就表示刪除節點的時候不移動其他節點
    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;
        //如果table不爲null並且次hash對應的數組節點上有值
        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);
                }
            }
            //node!=null並通過傳進來的matchValue來選擇需不需要對value進行校驗
            if (node != null && (!matchValue || (v = node.value) == value ||
                                 (value != null && value.equals(v)))) {
                //如果是樹節點,就調用removetreeNode
                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
                --size;
                //空方法
                afterNodeRemoval(node);
                return node;
            }
        }
        //沒找到就返回null
        return null;
    }

resize方法

final Node<K,V>[] resize() {
        Node<K,V>[] oldTab = table;
        //如果oldTable爲null,就爲0,否則就是oldTable.length
        int oldCap = (oldTab == null) ? 0 : oldTab.length;
        int oldThr = threshold;
        int newCap, newThr = 0;
        //如果不是空table
        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
        }
        //如果爲空table但oldThr>0,那麼初始容量就使用以前的閾值
        else if (oldThr > 0) 
            newCap = oldThr;
        //如果threshold並且threshold被默認賦值爲0(也就是沒有進行table的初始化),那麼就進行table初始化
        else {               
            newCap = DEFAULT_INITIAL_CAPACITY;
            newThr = (int)(DEFAULT_LOAD_FACTOR * DEFAULT_INITIAL_CAPACITY);
        }
        //上一步對table初始化的時候並沒有對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;
        //對oldTab進行遍歷並把值移動到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)
                        //使用e.hash對newCap-1進行與,而不是oldCap
                        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需不需要進行移動,因爲容量變了,爲了保證正確性(如果是小於oldCap的數,結果就會爲0)
                            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);
                        //進行尾插(1.7是頭插)
                        if (loTail != null) {
                            loTail.next = null;
                            newTab[j] = loHead;
                        }
                        //需要移動的偏移量是oldCap
                        if (hiTail != null) {
                            hiTail.next = null;
                            newTab[j + oldCap] = hiHead;
                        }
                    }
                }
            }
        }
        return newTab;
    }


 
//樹的修剪
//index表示修剪的開始,bit代表修剪的位數
final void split(HashMap<K,V> map, Node<K,V>[] tab, int index, int bit) {
            TreeNode<K,V> b = this;
            // Relink into lo and hi lists, preserving order
            //減爲兩棵樹
            TreeNode<K,V> loHead = null, loTail = null;
            TreeNode<K,V> hiHead = null, hiTail = null;
            int lc = 0, hc = 0;
            for (TreeNode<K,V> e = b, next; e != null; e = next) {
                next = (TreeNode<K,V>)e.next;
                e.next = null;
                //如果e.hash & bit就放到LTree
                if ((e.hash & bit) == 0) {
                    if ((e.prev = loTail) == null)
                        loHead = e;
                    else
                        loTail.next = e;
                    loTail = e;
                    ++lc;
                }
                //否則就放到HTree
                else {
                    if ((e.prev = hiTail) == null)
                        hiHead = e;
                    else
                        hiTail.next = e;
                    hiTail = e;
                    ++hc;
                }
            }
            //元素個數小於等於6就會還原爲鏈表
            if (loHead != null) {
                if (lc <= UNTREEIFY_THRESHOLD)
                    tab[index] = loHead.untreeify(map);
                else {
                    tab[index] = loHead;
                    if (hiHead != null) // (else is already treeified)
                        loHead.treeify(tab);
                }
            }
            //給index+bit(也就是原數組容量)就是HTree放的位置(也就是放在了修剪範圍之外)
            if (hiHead != null) {
                if (hc <= UNTREEIFY_THRESHOLD)
                    tab[index + bit] = hiHead.untreeify(map);
                else {
                    tab[index + bit] = hiHead;
                    if (loHead != null)
                        hiHead.treeify(tab);
                }
            }
        }

讀到這,我相信HashMap裏面比較難理解的代碼都基本掌握了!

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