HashMap部分源碼分析:

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

    private static final long serialVersionUID = 362498820763181265L;


    //容量必須是2的指數次冪
    static final int DEFAULT_INITIAL_CAPACITY = 1 << 4; // aka 16

    //hashMap的最大容量爲2^30次方
    static final int MAXIMUM_CAPACITY = 1 << 30;

    //默認的負載因子爲0.75
    static final float DEFAULT_LOAD_FACTOR = 0.75f;

    //當鏈表中元素的數量到達8的時候,鏈表會轉換成紅黑樹結構
    static final int TREEIFY_THRESHOLD = 8;

   //當bucket中的元素個數小於6的時候,紅黑樹結構轉換成鏈表結構
    static final int UNTREEIFY_THRESHOLD = 6;

   //當HashMap中存在紅黑樹時,HashMap中數組(table)的最小容量爲64
    static final int MIN_TREEIFY_CAPACITY = 64;

    //hash表中存儲的每一個Node元素
    static class Node<K,V> implements Map.Entry<K,V> {
        final int hash;//元素的hash值
        final K key;
        V value;
        Node<K,V> next;//該node節點的下一個節點

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

   /**
        key的hash值右移16位的原因:從putVal方法中可以看出,hashMap添加元素時,確認數組索引是用(p = tab[i = (n - 1) & hash]),
        又因爲n必須是2的整數次冪,所以n的表現形式只能是01111這種形式,所以當(n-1)與hash進行 與 運算時,起決定性作用的永遠是hash。
        01010010101000100101001100101010101
                                      01111
        ------------------------------------
        並且如上圖所示,hash的32位二進制數中,能夠起到運算作用的也只有後幾位,這樣計算出來的hash值重複率比較高。
        所以需要讓key.hashCode()右移16位,然後與自身進行  異或  運算。這樣做可以降低hash值的重複率。
   
   **/
    static final int hash(Object key) {
        int h;
        return (key == null) ? 0 : (h = key.hashCode()) ^ (h >>> 16);
    }

    /**
     * Returns x's Class if it is of the form "class C implements
     * Comparable<C>", else null.
     */
    static Class<?> comparableClassFor(Object x) {
        if (x instanceof Comparable) {
            Class<?> c; Type[] ts, as; Type t; ParameterizedType p;
            if ((c = x.getClass()) == String.class) // bypass checks
                return c;
            if ((ts = c.getGenericInterfaces()) != null) {
                for (int i = 0; i < ts.length; ++i) {
                    if (((t = ts[i]) instanceof ParameterizedType) &&
                        ((p = (ParameterizedType)t).getRawType() ==
                         Comparable.class) &&
                        (as = p.getActualTypeArguments()) != null &&
                        as.length == 1 && as[0] == c) // type arg is c
                        return c;
                }
            }
        }
        return null;
    }

    /**
     * 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));
    }

    
     //該方法的作用是初始化臨界值的大小----->threshold,返回大於initialCapacity的最小的二次冪數值,
     //如果在構造方法中傳入的不是2的整數次冪,該方法會強制轉換成2的整數次冪
    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;
    }

   
     //存儲元素的數組,總是2的冪次倍---->就是hash表中的數組
    transient Node<K,V>[] table;

    /**
     * Holds cached entrySet(). Note that AbstractMap fields are used
     * for keySet() and values().
     */
    transient Set<Map.Entry<K,V>> entrySet;

    //HashMap中所有key-value對的數量
    transient int size;

    //它是一個計數器,HashMap的結構每修改一次,modCount++
    transient int modCount;

    //它是一個臨界值,當size變量達到這個臨界值的時候,HashMap會自動擴容。threshold = capacity * loadFactor
    int threshold;

    //負載因子,默認爲0.75
    final float loadFactor;
    //*--------------------------------------------------HashMap的構造方法------------------------------------------------------------------------*//
    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;
        //強制將初始化容量裝換成2的n次冪
        this.threshold = tableSizeFor(initialCapacity);
    }


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

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

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

     //該函數的作用是將m集合中的所有元素全部放入到該HashMap實例中
    final void putMapEntries(Map<? extends K, ? extends V> m, boolean evict) {
        int s = m.size();
        if (s > 0) {
            if (table == null) { // pre-size
                float ft = ((float)s / loadFactor) + 1.0F;
                int t = ((ft < (float)MAXIMUM_CAPACITY) ?
                         (int)ft : MAXIMUM_CAPACITY);
                if (t > threshold)
                    threshold = tableSizeFor(t);
            }
            else if (s > threshold)
                resize();
            for (Map.Entry<? extends K, ? extends V> e : m.entrySet()) {
                K key = e.getKey();
                V value = e.getValue();
                putVal(hash(key), key, value, false, evict);
            }
        }
    }

   //返回當前<key,value>的數量
    public int size() {
        return size;
    }

  
    public boolean isEmpty() {
        return size == 0;
    }

   //提供的對外訪問的方法,內部調用的getNode();
    public V get(Object key) {
        Node<K,V> e;
        return (e = getNode(hash(key), key)) == null ? null : e.value;
    }

    /*
        getNode的過程:1:首先判斷當前HashMap是否爲空並且根據key的Hash值判斷當前索引處是否爲空,若不爲空,繼續查找,爲空,返回null
                     2:然後判斷當前索引處的第一個元素是否與要找的元素相等,如果相等,返回第一個數據,若不等,繼續查找
                     3:判斷當前節點是否是紅黑樹結構,若是,遍歷紅黑樹。若不是,遍歷鏈表
    */
    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;
    }

   //判斷HashMap中是否包含當前的key,實際調用getNode();
    public boolean containsKey(Object key) {
        return getNode(hash(key), key) != null;
    }

  //對外提供的向HashMap中添加元素的方法,內部實際調用的是putVal();
    public V put(K key, V value) {
        return putVal(hash(key), key, value, false, true);
    }

   /*
    putVal的過程:(1)首先將node[] table 復值給一個空的數組 tab 判斷tab[]是否爲空,爲null則進行擴容操作,不爲null,利用key的Hash&(n-1)確定該元素在數組中的位置。
                 (2)判斷該位置是否已經存在元素,若爲null,則直接添加,不爲null,判斷當前元素的key與已有元素的key的hash和equals是否相等,若相等,則進行覆蓋,返回oldVal
                 (3)若不相等,繼續判斷要加入的NOde是否屬於紅黑樹結構,若屬於,則以紅黑樹的方式進行添加操作,若不屬於,則遍歷後面的鏈表。
                 (4)若與鏈表中的某個元素相等,則進行覆蓋,若不等,則添加到鏈表的最後面。
                 (5)添加完以後判斷當前鏈表中元素的個數,有沒有達到鏈表轉換爲紅黑樹的臨界值(默認爲8),若達到,則轉換。
                 (6)最後判斷hash表中的元素個數size,有沒有達到擴容的臨界值,若達到,則擴容。threshold = loadFactor * capacity
   */
    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;
                }
            }
            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;
    }

    /**
     * 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
     
     初始化或者翻倍表大小。
     * 如果表爲null,則根據存放在threshold變量中的初始化capacity的值來分配table內存
     * (這個註釋說的很清楚,在實例化HashMap時,capacity其實是存放在了成員變量threshold中,
     * 注意,HashMap中沒有capacity這個成員變量)
     * 。如果表不爲null,由於我們使用2的冪來擴容,
     * 則每個bin元素要麼還是在原來的bucket中,要麼在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
                        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;
    }

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