1. 程式人生 > >HashMap源碼分析

HashMap源碼分析

warning boolean length table 優點 HA 包含 oat types

在java中,hashmap是一種非常重要的數據結構,現在我們來分析一下它的實現邏輯。

我們知道hashmap是存儲鍵值對的結構,它的存儲和查詢都很快,而基於數組的ArrayList有較快的查詢速度,和基於鏈表的LinendList有很好的易修改性能

技術分享圖片

hashmap則是結合了這兩者的優點,大概長這樣

技術分享圖片

HashMap的成員變量

static final int DEFAULT_INITIAL_CAPACITY = 1 << 4;//16 數組初始大小

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; transient Node<K,V>[] table;//數據實際存儲位置,node數組 transient Set<Map.Entry<K,V>> entrySet;// transient
int size;//鍵值對數量 transient int modCount;//修改次數 int threshold;//閾值--數組擴容相關 final float loadFactor;//加載因子

HashMap構造函數

    public HashMap(int initialCapacity, float loadFactor) {
        if (initialCapacity < 0)//初始容量不能小於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); }

HashMap的存儲單元

包含一個hash值,Key Value 和下一個節點引用

    static class Node<K,V> implements Map.Entry<K,V> {
        final int hash;
        final K key;//確保key不會被修改
        V value;
        Node<K,V> next;//鏈表結構,持有下一個元素的引用,方便獲取下一個元素

        Node(int hash, K key, V value, Node<K,V> next) {
            this.hash = hash;
            this.key = key;
            this.value = value;
            this.next = next;
        }

        public final K getKey()        { return key; }
        public final V getValue()      { return value; }
        public final String toString() { return key + "=" + value; }

        public final int hashCode() {
            return Objects.hashCode(key) ^ Objects.hashCode(value);
        }

        public final V setValue(V newValue) {
            V oldValue = value;
            value = newValue;
            return oldValue;
        }

        public final boolean equals(Object o) {
            if (o == this)
                return true;
            if (o instanceof Map.Entry) {
                Map.Entry<?,?> e = (Map.Entry<?,?>)o;
                if (Objects.equals(key, e.getKey()) &&
                    Objects.equals(value, e.getValue()))
                    return true;
            }
            return false;
        }
    }

HashMap 添加鍵值對

    public V put(K key, V value) {
        return putVal(hash(key), key, value, false, true);
    }

  //1.計算hash值
static final int hash(Object key) { int h; return (key == null) ? 0 : (h = key.hashCode()) ^ (h >>> 16); } 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)//計算數組下標,獲取這個下標的對象,若為空,存入新對象 tab[i] = newNode(hash, key, value, null); else {//若這個下標已經有了對象 Node<K,V> e; K k; if (p.hash == hash && ((k = p.key) == key || (key != null && key.equals(k))))//判斷hash值和key是否和這個對象的一樣,如果一樣說明key是一樣,替換原有鍵值對 e = p; else if (p instanceof TreeNode)//如果不一樣(hash沖突),判斷是否是樹型節點 e = ((TreeNode<K,V>)p).putTreeVal(this, tab, hash, key, value);//插入樹型節點 else {//hash沖突,非樹型節點,往鏈表後插入數據 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))))//hash相同 鍵相同 跳出循環處理 break; p = e;//指針下移 } } 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(); afterNodeInsertion(evict); return null; } 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 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; } 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); } }

有幾個值得註意的點:

1.hash值計算

h = key.hashCode()) ^ (h >>> 16

這是將int類型的值右移16位,得到的h 和int的所有位數相關,保證了散列性(降低hash沖突可能性)。

2.數組下標計算

i = (n - 1) & hash

這裏使用 & 保證下標不會超出 n - 1,& hash 保證了下標的散列性

HashMap源碼分析