從源碼分析HashMap的實現原理

HashMap整體分析

 HashTable繼承Map接口,提供了map中所有的操作並且等價於HashMap,除了它是多線程的並且允許爲多個null值。
 
 基礎的操作爲get、put操作,通過hash函數將元素放到桶中,遍歷集合需要時間去計算HashMap的容量(桶的數量以及key-value中值的數量)最重要的是設定初始化的容量

 HashMap有兩個重要參數:初始化容量、加載因子。
 在HashTable中容量就是桶的數量
 當這個當前數量在HashTable中超出了在加載因子和當前容量的值,Hashtable會重新進行hash(數據重新排列)
 因此HashTable大約有兩次計算桶的操作。

 默認的加載因子是0.75,這個值是保證空間和時間的消耗都是穩定的。加載因子過高會降低空間的管理時間,但是增加了查找的時間(影響到的操作有HashMap中的get、put操作)
 這是在Map中最期望的大小並且當初始化容量時就應該設定加載因子,目的時減少重新hash的數量。如果初始化容量比被加載因子分隔開的最大的值要更合適,那麼重新hash操作將不會出現。
 
 
 需要注意的是HashMap不是同步的也就是不支持多線程,也就是隻有一個線程在當前map中執行。
 如果大量的線程執行在一個HashMap中,通常通過多線程對象來封裝這個map完成多線程問題。
 
 如果不存在這樣的對象,那麼可以使用Collections中的synchronizedMap方法,
 方法如下:Map m = Collections.synchronizedMap(new HashMap(...));


1、默認值的分析

    
	 //初始化容量
    static final int DEFAULT_INITIAL_CAPACITY = 1 << 4; // aka 16

    
	 //最大容量
    static final int MAXIMUM_CAPACITY = 1 << 30;

    
	 //默認加載因子
    static final float DEFAULT_LOAD_FACTOR = 0.75f;

    
	 //鏈表轉紅黑樹的閾值值,意思爲當存儲的值必須大於2並且至少爲8,這是爲了減少樹向鏈表轉換時的收縮率。
    static final int TREEIFY_THRESHOLD = 8;

    
	 //樹轉換爲鏈表的閾值
    static final int UNTREEIFY_THRESHOLD = 6;

    
	 //初始化容量的大小,這個值最小爲4*6(紅黑樹轉換鏈表的閾值)這是爲了避免重新調整大小以及設定閾值的複雜化。
    static final int MIN_TREEIFY_CAPACITY = 64;

    
	 //Node節點類,繼承Map.Entry類,並且定義了equals方法,用來比較兩個值是否相等。
    static class Node<K,V> implements Map.Entry<K,V> {
        final int hash;
        final K 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;
        }
    }

	 //hash函數,用來計算key值的hash值
    static final int hash(Object key) {
        int h;
        return (key == null) ? 0 : (h = key.hashCode()) ^ (h >>> 16);
    }

    

    /**
     * Returns k.compareTo(x) if x matches kc (k's screened comparable
     * class), else 0.
     */
    @SuppressWarnings({"rawtypes","unchecked"}) // for cast to Comparable
    static int compareComparables(Class<?> kc, Object k, Object x) {
        return (x == null || x.getClass() != kc ? 0 :
                ((Comparable)k).compareTo(x));
    }

   
	 //計算大小的方法,每次都是2的倍數,如果設定大小爲10,那麼會尋找大於10的2的倍數,也就是16,一次類推
	 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;
    }

    /* ---------------- Fields -------------- */

    
	 //初始化map時調用
    transient Node<K,V>[] table;

    
    
	 //在map中key-value數量的大小
    transient int size;

  

   
	//閾值,大於當前閾值,需要增加容量,通過最大容量和加載因子的乘積計算出
    int threshold;

    
	 //加載因子的表
    final float loadFactor;

    
	 //有參構造函數,初始化threshold的值,通過初始化容量以及加載因子設定
    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);
    }

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

    //無參構造函數
    public HashMap() {
        this.loadFactor = DEFAULT_LOAD_FACTOR; // all other fields defaulted
    }

    
	 //參數爲一個Map,設定加載因子,然後執行putMapEntries方法來遍歷參數Map的值,放到新的Map中
    public HashMap(Map<? extends K, ? extends V> m) {
        this.loadFactor = DEFAULT_LOAD_FACTOR;
        putMapEntries(m, false);
    }

2、get方法分析

	//get方法,通過key獲取value,調用hash方法來計算key的hashcode,將hashcode作爲參數調用getNode方法
    public V get(Object key) {
        Node<K,V> e;
        return (e = getNode(hash(key), key)) == null ? null : e.value;
    }
	 //通過key來判斷是否包含該值,依然需要調用hash函數來計算hashcode進行判斷
    public boolean containsKey(Object key) {
        return getNode(hash(key), key) != null;
    }

    
	 //先判斷第一個是否爲要查詢的值,如果是則返回,否則繼續遍歷下一個節點,判斷節點是否在TreeNode節點中
	 //如果在TreeNode節點中,則該節點是紅黑樹的結構,則需要調用getTreeNode方法來查詢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) {
            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;
    }

3、put方法分析

 //put方法,在put方法中調用了putVal方法,putVal方法最終執行put操作。
    public V put(K key, V value) {
        return putVal(hash(key), key, value, false, true);
    }

    /**
     * Implements Map.put and related methods.
     *
     * @param hash hash for key
     * @param key the key
     * @param value the value to put
     * @param onlyIfAbsent if true, don't change existing value
     * @param evict if false, the table is in creation mode.
     * @return previous value, or null if none
     */
	 //該方法爲final類型,不可繼承不可重寫,四個參數分別爲:key的hashcode、key、value、是否更改現有的值、判斷上一個值如果沒有則爲null
    final V putVal(int hash, K key, V value, boolean onlyIfAbsent,
                   boolean evict) {
        Node<K,V>[] tab; Node<K,V> p; int n, i;
		//判斷是否爲map是否爲null,如果爲null則計算大小。
        if ((tab = table) == null || (n = tab.length) == 0)
            n = (tab = resize()).length;
			//判斷鏈表中是否有該值,若沒有則重新創建一個Node節點。
        if ((p = tab[i = (n - 1) & hash]) == null)
            tab[i] = newNode(hash, key, value, null);
        else {
		//如果有該值,則判斷hash值是否相同,若相同再通過equals判斷值是否相等
            Node<K,V> e; K k;
            if (p.hash == hash &&
                ((k = p.key) == key || (key != null && key.equals(k))))
                e = p;
				//判斷是否爲樹節點,如果爲樹節點則調用putTreeVal方法進行put值
            else if (p instanceof TreeNode)
                e = ((TreeNode<K,V>)p).putTreeVal(this, tab, hash, key, value);
				//此處是判斷鏈表轉紅黑樹的操作,該操作中通過在循環中判斷鏈表中的大小是否大於了8,如果大於等於7則執行treeifyBin方法進行鏈表轉紅黑樹操作。
            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) { // 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;
    }

4、擴容分析

 /**
     * Initializes or doubles table size.  If null, allocates in
     * accord with initial capacity target held in field threshold.
     * Otherwise, because we are using power-of-two expansion, the
     * elements from each bin must either stay at same index, or move
     * with a power of two offset in the new table.
     *
     * @return the table
     */
	 //重新計算大小的方法,該方法中每次擴容時都會擴大兩倍。
    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數組
        Node<K,V>[] newTab = (Node<K,V>[])new Node[newCap];
        table = newTab;
		//將原來的Node數組的值放到新的Node數組中
        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)
					//每次擴容都是2的倍數,因此將值放在新數組中,通過hash值與新數組的長度進行 與 操作計算位置,因此影響位置的數據只有最高位的一位。
					//比如擴容前的大小爲8,數據A的hash值爲0111,則定位爲0011&(8-1)=0111&7=0111&111 = 0011
					//擴容後的大小爲16,數據A重新計算位置,則0011&(16-1)=0111&1111=0011,兩次的位置相同
					//因此通過e.hash&oldCap,0011&8=0011&1000=0,表示數據A的位置沒有發生變化。
                        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;
							//該操作不需要重新計算hash,此處通過hash與原來的長度進行 與 操作,根據結構是否爲0來做對應的處理
							//如果是0則位置沒有發生變化,如果不爲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;
    }

5、鏈表轉紅黑樹分析

	 //鏈表轉紅黑樹的方法
    final void treeifyBin(Node<K,V>[] tab, int hash) {
        int n, index; Node<K,V> e;
		//判斷數組的大小是否小於64,如果小於執行擴容操作,否則執行鏈表轉紅黑樹的操作。
        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);
        }
    }
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章