HashMap源碼淺解

HashMap作爲日常開發中,常用的數據類型,給開發帶來了很多的便利。但是爲了不做一個只用調用API的碼農,理解HashMap的實現也是很有必要的。

本文講解的是 JDK1.8 中的HashMap,相對於之前的版本,JDK1.8中最大的改變就是數據存儲的方式。

1.8之前如果產生 hash衝突,解決辦法是使用鏈表,但是如果 hash衝突嚴重的話,get() 方法的時間複雜度會從O(1)變成 O(n) ;1.8之後加入了 紅黑樹,當衝突的數據較少時,仍然使用 鏈表 ,較多時則改用 紅黑樹

HashMap接收一個鍵值對作爲存儲內容,在定義時需要指定泛型,也是爲了數據存取的安全。

Map<String, String> m = new HashMap<>();
//or
HashMap<String, String> m = new HashMap<>(5);

HashMap的構造函數:

/**
* The load factor used when none specified in constructor.
*/
static final float DEFAULT_LOAD_FACTOR = 0.75f;

/**
* The maximum capacity, used if a higher value is implicitly specified
* by either of the constructors with arguments.
* MUST be a power of two <= 1<<30.
*/
static final int MAXIMUM_CAPACITY = 1 << 30;

public HashMap() {
    this.loadFactor = DEFAULT_LOAD_FACTOR; // all other fields defaulted
}

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

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;
    this.threshold = tableSizeFor(initialCapacity);
}

當調用無參構造時,加載因子 loadFactor 爲默認值 0.75f 

什麼是加載因子?HashMap是基於數組和鏈表及紅黑樹構建的,當添加鍵值對時,會佔用數組的空間,假設默認的數組大小爲 16 ,16 * 0.75 = 12,當添加的元素數量大於等於12時,會重新新建一個更大數組存放元素以及rehashing(再哈希)。當然這也是一個費事的操作,所以應該根據需求,確定初始容量。這就用到了 HashMap(int) 構造函數。

HashMap(int) 給一個 int 類型的參數,作爲初始容量大小,HashMap(int) 中再次調用 HashMap(int, float)構造函數。第一個爲 初始容量 ,第二個爲 加載因子 。再看 HashMap(int, float) 。

當傳入的 初始容量 小於 0 ,拋出 IllegalArgumentException 異常,而且容量最大1<<30 即 1073741824加載因子 小於等於 0 ,或者是一個非數字(NaN),同樣拋出 IllegalArgumentException 異常;如果兩個參數都合法,則初始化成功。

有趣的是,最後一行代碼:this.threshold = tableSizeFor(initialCapacity);

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;
}

對於傳入的 初始容量 的賦值,是調用 tableSizeFor(int) 方法的返回值,而不是我們指定的大小。假如我們這樣:

//    初始容量爲 10 , 加載因子爲 0.7
Map<String, Object> map = new HashMap<>(10, 0.7f);

我們指定初始容量爲 10 ,但是經過 tableSizeFor(int) 方法之後,返回值變爲 16 ,剛好爲 2 的整數次方。即初始容量爲16。這是爲什麼呢?毋庸置疑,這樣做一定是爲了優化,也就是提高效率。在 putVal(int hash, K key, V value, boolean onlyIfAbsent, boolean evict) 方法中。當添加元素時,利用hash與容量做與運算。tab[i = (n - 1) & hash]n數組的大小,即HashMap的容量,也就是 2的整次冪,假設 n = 1616 - 1 的二級制碼爲 1111hash與運算時,效率會特別高,所以HashMap的容量爲 2的整次冪

putVal() 方法如下:

    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;
        if ((p = tab[i = (n - 1) & hash]) == null)            //hash未衝突則新建節點
            tab[i] = newNode(hash, key, value, null);
        else {
            Node<K,V> e; K k;
            if (p.hash == hash &&                  //當key相等時,替換value,並返回舊value
                ((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;
                }
            }
            if (e != null) { // 當key存在
                V oldValue = e.value;
                if (!onlyIfAbsent || oldValue == null)
                    e.value = value;
                afterNodeAccess(e);
                return oldValue;
            }
        }
        ++modCount;
        if (++size > threshold)  //當元素個數大於閾值,即size > capacity * DEFAULT_LOAD_FACTOR
            resize();
        afterNodeInsertion(evict);
        return null;
    }

其中有幾個重要的成員變量:

//    默認初始容量
static final int DEFAULT_INITIAL_CAPACITY = 1 << 4; // aka 16  
//    最大容量,即 1073741824
static final int MAXIMUM_CAPACITY = 1 << 30;
//    默認加載因子
static final float DEFAULT_LOAD_FACTOR = 0.75f;
//    threshold = capacity * DEFAULT_LOAD_FACTOR
int threshold;

再來看 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;
        if ((tab = table) != null && (n = tab.length) > 0 &&
            (first = tab[(n - 1) & hash]) != null) {    //根據哈希值得到位置索引,如果存在且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) {    //hash衝突,1.8之後用鏈表和紅黑樹解決哈希衝突,當 first 是 TreeNode 類型時,從樹中查找元素
                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;
    }

 

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