Java源碼分析 - HashMap 源碼分析

HashMap 簡介

HashMap 實現了Map接口,允許null key或者null value,與HashTable相似,但是HashTable 不允許空值並且是線程安全的。

HashMap get與put都可以在常數時間內執行,即爲O(1)。

影響HashMap的性能有兩個因素:Capacity 和 load factor, Capacity是hashtable的桶的數量,load factor 是在擴容之前桶可以裝滿的程度。當數量超過factor*Capacity 的時候,hashmap擴容爲接近桶數量的二倍。

HashMap非線程安全,可以包裝在自定義的線程安全的類中,或者使用Collections.synchronizedMap方法

Map m = Collections.synchronizedMap(new HashMap(...));

構造方法

HashMap 可實例化時指明 loadFactor,如果未指明設爲默認值,如果指明瞭initialCapacity會計算出閾值threshold。
HashMap()
HashMap(int initialCapacity)
HashMap(int initialCapacity, float loadFactor)
HashMap(Map<? extends K, ? extends V> m)

tableSizeFor() 方法可以返回大於cap的最小的2的冪值。方法爲把所有位的值置爲1,然後把結果加1。
eg. cap = 10100
n = 10100 | 1010
n = 11110 | 111
n = 11111 | 11

n+1 = 100000

    /**
     * Returns a power of two size for the given target capacity.
     */
    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;
        return (n < 0) ? 1 : (n >= MAXIMUM_CAPACITY) ? MAXIMUM_CAPACITY : n + 1;
    }

HashMap hash函數

高低位共同參與運算,使hashmap分佈更加均勻,降低hash衝撞。

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

resize方法

resize 初始化table或者擴容,樹化,鏈表化
resize 重新定義或者初始化參數,如果需要擴容,容量,閾值都擴大一倍(最大值範圍內),將舊錶的值轉移到新表。遍歷所有位置,如果該位置爲不爲空且只有一個值,將該值放置新表 hash&(新容量-1) 位。如果該位置已經樹化,調用TreeNode.split方法,如果該位置已經鏈表化,使用 hash&舊容量 區分高低位,低位放置原處,高位放置於 舊容量+原下標處。

    final Node<K,V>[] resize() {
    	// oldTab 當前的桶
        Node<K,V>[] oldTab = table;
       //當前桶的個數,閾值,創建int新容量和新閾值
        int oldCap = (oldTab == null) ? 0 : oldTab.length;
        int oldThr = threshold;
        int newCap, newThr = 0;
        //如果當前容量大於0
        if (oldCap > 0) {
            // 當前容量超過最大容量,閾值設爲最大,不再擴容
            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);
        }
        // 如果新閾值是0,表爲空,初始化指定了容量和閾值或容量
        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) {
                    // 舊桶置爲空,GC
                    oldTab[j] = null;
                    // 如果鏈表只有一個元素,更新至新桶,位置爲 hash & (新容量-1)                    
                    if (e.next == null)
                    // 桶容量爲2的冪數,相當於取模
                        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;
                            // 利用位運算,取得哈希值去模之後的值
                            // 如果爲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);
                        // 將低位鏈表放置原位置
                        if (loTail != null) {
                            loTail.next = null;
                            newTab[j] = loHead;
                        }
                        // 將高位鏈表放置 原位置+舊容量
                        if (hiTail != null) {
                            hiTail.next = null;
                            newTab[j + oldCap] = hiHead;
                        }
                    }
                }
            }
        }
        return newTab;
    }

put 方法

put方法調用hash() 方法,高低位共同參與計算。

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;
        // 如果現表爲空,初始化
        if ((tab = table) == null || (n = tab.length) == 0)
            n = (tab = resize()).length;
        // 如果現表 (n-1)&hash 爲空,實例化新結點
        if ((p = tab[i = (n - 1) & hash]) == null)
            tab[i] = newNode(hash, key, value, null);
        else {
            Node<K,V> e; K k;
            // 如果發生了碰撞,並且key相同,記錄該點
            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相同的節點,記錄該點
                    if (e.hash == hash &&
                        ((k = e.key) == key || (key != null && key.equals(k))))
                        break;
                    p = e;
                }
            }
            // 如果找到需要覆蓋的節點,如果onlyIfAbsent爲false或者原值爲空,覆蓋
            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();
        // 空方法,LinkedHashMap重寫
        afterNodeInsertion(evict);
        return null;
    }

get 方法

    final Node<K,V> getNode(int hash, Object key) {
        Node<K,V>[] tab; Node<K,V> first, e; int n; K k;
        // 如果table非空,並且在 hash&(n-1) 處有值
        if ((tab = table) != null && (n = tab.length) > 0 &&
            (first = tab[(n - 1) & hash]) != null) {
            // 如果首屆點的key值等於傳入的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;
    }

remove方法

    public V remove(Object key) {
        Node<K,V> e;
        return (e = removeNode(hash(key), key, null, false, true)) == null ?
            null : e.value;
    }
// matchValue 如果爲 true, 當value值同時,移除節點
// movable 如果爲 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;
        if ((tab = table) != null && (n = tab.length) > 0 &&
            (p = tab[index = (n - 1) & hash]) != null) {
            // node用於記錄 是否有key值相同的值
            Node<K,V> node = null, e; K k; V v;
            // 如果 (n-1)&hash 位有值,賦值爲p;key值同,則證明找到了key值相同的該位置節點。賦值爲node。
            if (p.hash == hash &&
                ((k = p.key) == key || (key != null && key.equals(k))))
                node = p;
           // 如果 key值不等,且p有子節點,證明已經鏈化或者樹化
            else if ((e = p.next) != null) {
            // 如果 p已經樹化,使用紅黑樹的遍歷方式
                if (p instanceof TreeNode)
                    node = ((TreeNode<K,V>)p).getTreeNode(hash, key);
             // 如果已經鏈化,循環遍歷鏈表,如果找到 key 值相同的,賦值給node
                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,並且如果 matchValue 值爲 true時,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);
                // 如果已經鏈化,且第一位爲node,將指針指到 node.next
                // 或者沒有鏈化,將該位賦值爲 null (node.next)
                else if (node == p)
                    tab[index] = node.next;
                // 否則將p的下一位賦值爲node下一位
                else
                    p.next = node.next;
                ++modCount;
                --size;
                // 定義一個callback
                afterNodeRemoval(node);
                return node;
            }
        }
        return null;
    }

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