HashMap 1.8源碼分析

  • 成員變量以及構造函數

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

    private static final long serialVersionUID = 362498820763181265L;

	//初始容量16
    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;

 
    //鏈表轉樹的門閥值
    static final int TREEIFY_THRESHOLD = 8;

    
    //樹轉鏈表的門閥值
    static final int UNTREEIFY_THRESHOLD = 6;

    //鏈表轉樹時需要滿足鏈表長度達到8以及容量達到64
    //前期因爲容量小,所以hash衝突嚴重,當長度達到8時,
    //如果容量沒有達到64,那麼不會將鏈表轉成樹,而是會先擴容
    static final int MIN_TREEIFY_CAPACITY = 64;

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

    //將高位與低位異或操作然後保存在低位,因爲一般只用到低位
    static final int hash(Object key) {
        int h;
        return (key == null) ? 0 : (h = key.hashCode()) ^ (h >>> 16);
    }
    //找到大於參數cap的最小的二次的冪
	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;
    }

    //存放數據的桶
    transient Node<K,V>[] table;

  
    transient Set<Map.Entry<K,V>> entrySet;

    
    transient int size;

    //記錄修改次數,相當於版本號
    transient int modCount;

    
    int threshold;

    //加載因子
    final float loadFactor;

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

   
    public HashMap(Map<? extends K, ? extends V> m) {
        this.loadFactor = DEFAULT_LOAD_FACTOR;
        putMapEntries(m, false);
    }
  • get()方法

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;
    }
  • put()方法

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))))
                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;
                }
            }
            //覆蓋value,這裏統一處理
            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;
    }
  • 擴容

    擴容較1.7有了一下幾個改進:
    1. 使用尾插法,鏈表元素的相對順序不會改變,並且併發情況下不會因爲逆序而導致死循環
    2. 擴容轉移元素時,不需要再計算hash
final Node<K,V>[] resize() {
		......................................省略
        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 { 
                    	// loHead,loTail構成的鏈表用來保存擴容時位置不改變的元素
                    	Node<K,V> loHead = null, loTail = null;
                    	//  hiHead, hiTail構成的鏈表用來保存擴容時位置發生改變的元素
                        Node<K,V> hiHead = null, hiTail = null;
                        Node<K,V> next;
                        do {
                            next = e.next;
                            //這裏舉個例子,假設原數組容量16,截取低四位
                            //元素A的hash值爲  001111,由於其第五位爲0,所以擴容時位置不變
                            //元素B的hash值爲  011111,由於其第五位爲1,原位置截取四位爲1111,
                            //擴容時新位置截取五位爲爲11111,說到這裏之後的邏輯都不難了.
                            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;
    }
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章