源碼剖析(一) HashMap

用了2年的hashmap,一直都是看別人的博文,懂了一點原理,今天點進 jdk1.8 的源碼,從頭理順它。

  1. 從數據結構上來看,hashmap採用數組+鏈表+紅黑樹(當hashmap的size >= 64 && 單個鏈表長度>8 )的方式來達到最快的訪問速度
  2. 從算法上來看,hashmap最主要的就是採用了hash算法

HashMap類的屬性

// 默認的初始容量是16
    static final int DEFAULT_INITIAL_CAPACITY = 1 << 4;   
    // 最大容量
    static final int MAXIMUM_CAPACITY = 1 << 30; 
    // 默認的填充因子
    static final float DEFAULT_LOAD_FACTOR = 0.75f;
    // 結點數大於這個值(並且size > 64時)時會轉成紅黑樹,泊松分佈的計算公式,鏈表中元素個數爲8時的概率已經非常小
    static final int TREEIFY_THRESHOLD = 8; 
    // 當桶(bucket)上的結點數小於這個值時樹轉鏈表
    static final int UNTREEIFY_THRESHOLD = 6;
    // 桶中結構轉化爲紅黑樹對應的table的最小大小
    static final int MIN_TREEIFY_CAPACITY = 64;
    // 存儲元素的數組,總是2的冪次倍
    transient Node<k,v>[] table; 
    // 具體元素的集
    transient Set<map.entry<k,v>> entrySet;
    // 元素的個數。
    transient int size;
    // 每次擴容和更改map結構的計數器
    transient int modCount;   
    // 臨界值 當實際大小(容量*填充因子)超過臨界值時,會進行擴容
    int threshold;
    // 填充因子 
    final float loadFactor;

 

Hash算法

static final int hash(Object key) {
        int h;
        return (key == null) ? 0 : (h = key.hashCode()) ^ (h >>> 16);
    }
  1. 初始化h
  2. 調用object類的hashCode方法,算出值
  3. 將2得到的值轉換成二進制 右移16位,將高16位換到低16位,原高16位補0(使用高16位參與運算爲了降低hash衝突)
  4. 將2的值和3的值 做^(異或)運算
  5. 此方法當key!= null 時,返回4的值 

put()方法

final V putVal(int hash, K key, V value, boolean onlyIfAbsent,
                   boolean evict) {
        //tab 哈希桶   // p 哈希桶上的節點
        Node<K,V>[] tab; Node<K,V> p; int n, i;
        //如果table未初始化爲空 或者 table的長度爲0,執行resize()方法,初始化hashMap
        if ((tab = table) == null || (n = tab.length) == 0)
            n = (tab = resize()).length;
        //計算i=長度-1 和 hash值  進行與運算,相當於進行取模,拿到tab數組上的位置,判斷是否爲        
         空,爲空則新建一個Node對象,並放在tab數組上
        if ((p = tab[i = (n - 1) & hash]) == null)
            tab[i] = newNode(hash, key, value, null);

        //tab數組當前位置存在對象,產生了hash衝突
        else {
            Node<K,V> e; K k;
        //此時,p爲tab數組上與當前產生哈希碰撞的 Node對象
          //hash值相同,key值相同,直接覆蓋
            if (p.hash == hash &&
                ((k = p.key) == key || (key != null && key.equals(k))))
                e = p;
          //如果p是紅黑樹節點,那麼調用紅黑樹的put方法
            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);
                        //判斷鏈表長度是否 >= 8 - 1時,轉爲紅黑樹,跳出循環
                        if (binCount >= TREEIFY_THRESHOLD - 1) // -1 for 1st
                            treeifyBin(tab, hash);
                        break;
                    }
                    //// 判斷鏈表中結點的key值與插入的元素的key值是否相等
                    if (e.hash == hash &&
                        ((k = e.key) == key || (key != null && key.equals(k))))
                        break;
                    p = e;
                }
            }
            //找到key值和hash值都相同的點,直接替換value值,並返回
            if (e != null) { // existing mapping for key
                V oldValue = e.value;
                if (!onlyIfAbsent || oldValue == null)
                    e.value = value;
                afterNodeAccess(e);
                return oldValue;
            }
        }
        //結構性修改,記錄被修改的次數
        ++modCount;
        //如果 size值 大於閾值,擴容
        if (++size > threshold)
            resize();
        afterNodeInsertion(evict);
        return null;
    }

resize()方法

final Node<K,V>[] resize() {
        //初始化獲得原數組,oldCap原數組長度,oldTHr原閾值,newCap新長度, newThr新閾值
        Node<K,V>[] oldTab = table;
        int oldCap = (oldTab == null) ? 0 : oldTab.length;
        int oldThr = threshold;
        int newCap, newThr = 0;
        
        if (oldCap > 0) {
            //如果原數組長度>=最大容量,閾值爲Integer的最大,2的32次冪
            if (oldCap >= MAXIMUM_CAPACITY) {
                threshold = Integer.MAX_VALUE;
                return oldTab;
            }
            //新的數組長度爲原數組長度*2,新的閾值爲原閾值*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;
                //e爲原來的元素
                if ((e = oldTab[j]) != null) {
                    oldTab[j] = null;
                    //此處元素爲單個元素,新的位置爲hash & 長度-1
                    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;
                            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);

                        // 將分組後的鏈表映射到新桶中
                        //這種說明元素的hash 第5位爲0   類似00000000
                        if (loTail != null) {
                            loTail.next = null;
                            newTab[j] = loHead;
                        }
                        //這種說明元素的hash 第5位爲1   類似00010000
                        if (hiTail != null) {
                            hiTail.next = null;
                            newTab[j + oldCap] = hiHead;
                        }
                    }
                }
            }
        }
        return newTab;
    }

創建一個hashmap

Map map = new HashMap<>();

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