Java源碼解讀掃盲【集合--HashMap】

1、HashMap 簡介

     前面介紹了LinkedList和ArrayList兩個經常使用的集合,此次介紹的是另一個經常使用的集合HashMap。HashMap的數據結構都用到了數組和鏈表。HashMap繼承了AbstractMap, 實現了Map,Cloneable, Serializable接口,使用的是鍵(key)-值(value)對存儲方式,key和value都容許爲null,key不容許重複 。node

2、 HashMap 的數據結構

節點表示以下:算法

Node 只能用於鏈表的狀況,紅黑樹的狀況須要使用 TreeNode。數組

static class Node<K,V> implements Map.Entry<K,V> {
    final int hash;
    final K key;
    V value;
    Node<K,V> next;
}
static final class TreeNode<K,V> extends LinkedHashMap.Entry<K,V> {
    TreeNode<K,V> parent;  // red-black tree links
    TreeNode<K,V> left;
    TreeNode<K,V> right;
    TreeNode<K,V> prev;    // needed to unlink next upon deletion
    boolean red;
    TreeNode(int hash, K key, V val, Node<K,V> next) {
        super(hash, key, val, next);
    }
}

         JDK1.8以前的HashMap是使用數組 + 鏈表做爲數據結構,利用key的hashCode來計算hash值,再跟數組長度 - 1進行按位與得出在數組的下標,可是由於計算出來的下標有可能同樣,特別是在存儲的數量多的狀況下同樣的概率就更高了,因此在JDK1.8以前使用鏈表來存儲計算出來下標同樣的元素。可是鏈表的查詢速度較慢,在JDK1.8對HashMap作了優化,使用數組 + 鏈表 + 紅黑樹來存儲,當鏈表的長度大於8的時候,會轉成紅黑樹,紅黑樹是一種 平衡二叉查找樹 ,有較高的查找性能。 爲了閱讀HashMap源碼,特地去了解了下紅黑樹,有興趣的朋友能夠去了解下紅黑樹,       https://my.oschina.net/u/3737136/blog/1649433緩存

3、HashMap 源碼解析

public class HashMap<K,V> extends AbstractMap<K,V>
    implements Map<K,V>, Cloneable, Serializable {

    private static final long serialVersionUID = 362498820763181265L;

    /**
     * 默認初始化大小,值必須保證2次冪 - MUST be a power of two.
     */
    static final int DEFAULT_INITIAL_CAPACITY = 1 << 4; // aka 16 位運算效率最高

    /**
     * 最大容量,2次冪必須小於等於1<<30
     * MUST be a power of two <= 1<<30.
     */
    static final int MAXIMUM_CAPACITY = 1 << 30;

    /**
     * 負載因子
     */
    static final float DEFAULT_LOAD_FACTOR = 0.75f;

    /**
     * 鏈表的長度,當鏈表大於8時,有可能轉換成紅黑樹
     */
    static final int TREEIFY_THRESHOLD = 8;

    /**
     * 在容器進行擴容時發現紅黑樹的長度小於 6 時會轉回鏈表
     */
    static final int UNTREEIFY_THRESHOLD = 6;

    /**
     * 在轉變成樹以前,還會有一次判斷,當鍵-值對數量大於 64 纔會轉換。
     * 這是爲了不在哈希表創建初期,多個鍵-值對恰
     * 好被放入了同一個鏈表中而致使沒必要要的轉化
     */
    static final int MIN_TREEIFY_CAPACITY = 64;

     /**
     * 計算hash值 :假如數組的長度是 16 ,那計算出元素在數組中的存儲下標就是 hash & (16 - 1)
     * 也是是 hash & 1111 ,若是有兩個key,其生成的hashCode分別爲ABCD0000(8個16進制,32位),0ADC0000
     * 將這兩個hashCode(先轉成二進制)和 1111按位與的話,獲得的結果都是0,可是這兩個hashCode相差不少,但卻
     * 存在數組的同一個位置上,這樣會致使鏈表過長,而影響查詢速度,因此爲了減小這種狀況,因此這裏使用h >>> 16(無符號右移)
     */
    static final int hash(Object key) {
        int h;
        return (key == null) ? 0 : (h = key.hashCode()) ^ (h >>> 16);
    }

    /**
     * capacity必須知足2的N次方,若是在構造函數內指定的容量cap不知足,
     * 經過下面的算法將其轉換爲大於n的最小的2的N次方數.
     */
    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;
    }
/**
 *  Node節點的數組,主要容器
 */
transient Node<K,V>[] table;

/**
 *緩存entrySet()
 */
transient Set<Map.Entry<K,V>> entrySet;

/**
 * HashMap的大小,也就是存儲鍵-值對的數量
 */
transient int size;

/**
 * 修改次數
 */
transient int modCount;

/**
 * 閾值,threshold = 容量(table.length) * 負載因子,
 * 當HashMap中存儲的鍵-值對數量大於這個的時候進行擴容
 *
 * @serial
 */
int threshold;

// 負載因子,默認0.75f,負載因子越低的話容器中的空閒空間越多,衝突機會較少,查詢較快
// 負載因子越高的話容器中填滿的元素更多了,減小了空間的開銷,但元素跟元素之間的衝突就多了,衝突的話
// 會生成鏈表或紅黑樹,因此查詢就慢了
final float loadFactor;
/**
 * 在HashMap中的get方法就是調用該方法用key來獲取value
 * 經過key獲取對應存放的節點
 */
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) {
        // (n - 1) & hash 該元素在table中的下標,若是獲取到不爲null的話。
        // 獲取第一個(鏈表的頭或者紅黑樹的root)判斷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;
}
/**
 * HashMap中的put方法就是調用該方法來插入值
 * 若是onlyIfAbsent爲true的話,不改變已經存在的值
 * 若是evict爲false的話,說明該HashMap是剛建立的
 */
final V putVal(int hash, K key, V value, boolean onlyIfAbsent,
               boolean evict) {
    Node<K,V>[] tab; Node<K,V> p; int n, i;
    // 若是table爲null的話新建立一個table,這裏的resize()方法有兩個做用一個是新建立table,另外一個是擴容
    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 {
        // e :下面操做若是該key已經存在,則將該key對應的節點賦值給e
        Node<K,V> e; K k;
        // 若是key已經存在而且key對應的節點是在第一個的話,則使用已經存在的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);
        // 若是下標使用的是鏈表結構,則生成Node節點並添加到鏈表的尾部
        else {
            for (int binCount = 0; ; ++binCount) {
                if ((e = p.next) == null) {
                    p.next = newNode(hash, key, value, null);
                    // 若是鏈表長度大於8的話則轉換成紅黑樹
                    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;
            }
        }
        if (e != null) {  // 若是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;
}
/**
 * resize() 方法用於初始化數組或數組擴容,
 * 每次擴容後,容量爲原來的 2 倍,
 * 並進行數據遷移。
 */
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;
        }
        // 將數組大小擴大一倍
        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;
            if ((e = oldTab[j]) != null) {
                oldTab[j] = null;
                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
                    // 這塊是處理鏈表的狀況,
                    // 須要將此鏈表拆成兩個鏈表,放到新的數組中,而且保留原來的前後順序
                    // loHead、loTail 對應一條鏈表,hiHead、hiTail 對應另外一條鏈表,
                    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;
}
}
相關文章
相關標籤/搜索