源碼分析——HashMap的put,resize,containskey方法原理分析

HashMap的put方法

 /**
     * Associates the specified value with the specified key in this map.
     * If the map previously contained a mapping for the key, the old
     * value is replaced.
     *
     * @param key key with which the specified value is to be associated
     * @param value value to be associated with the specified key
     * @return the previous value associated with <tt>key</tt>, or
     *         <tt>null</tt> if there was no mapping for <tt>key</tt>.
     *         (A <tt>null</tt> return can also indicate that the map
     *         previously associated <tt>null</tt> with <tt>key</tt>.)
     */
    public V put(K key, V value) {
        return putVal(hash(key), key, value, false, true);
    }

1.map將指定的value和key關聯起來。

2.如果map之前包含key的映射,新的值會替換舊的值。

3.map支持null的key,null的value。

 

put方法裏面,

第一步:對key值進行hash算法操作。

   /**
     * Computes key.hashCode() and spreads (XORs) higher bits of hash
     * to lower.  Because the table uses power-of-two masking, sets of
     * hashes that vary only in bits above the current mask will
     * always collide. (Among known examples are sets of Float keys
     * holding consecutive whole numbers in small tables.)  So we
     * apply a transform that spreads the impact of higher bits
     * downward. There is a tradeoff between speed, utility, and
     * quality of bit-spreading. Because many common sets of hashes
     * are already reasonably distributed (so don't benefit from
     * spreading), and because we use trees to handle large sets of
     * collisions in bins, we just XOR some shifted bits in the
     * cheapest possible way to reduce systematic lossage, as well as
     * to incorporate impact of the highest bits that would otherwise
     * never be used in index calculations because of table bounds.
     */
    static final int hash(Object key) {
        int h;
        return (key == null) ? 0 : (h = key.hashCode()) ^ (h >>> 16);
    }

 

設計者設計hash算法的原因:1.權衡速度,效用,質量之間的均衡考慮。  2.目前的hash集合已經分配均勻,如果碰撞頻繁可以採用tree來處理。 3.高16位和低16位進行異或處理,系統損耗最小。計算細節如下:

 

 

 

 

第二步,分配容器,建立key和value的綁定關係


    /**
     * 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 V putVal(int hash, K key, V value, boolean onlyIfAbsent,
                   boolean evict) {
        //Node爲map的Map.Entry<K,V> 接口實現,有hash值,key值,value值,Node<K,V>四個參數構成
        Node<K,V>[] tab; Node<K,V> p; int n, i;

        //如果table爲null,則創建
        if ((tab = table) == null || (n = tab.length) == 0)
            n = (tab = resize()).length;

        //計算index位置
        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;
            //結構爲treeNode
            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) {
                V oldValue = e.value;
                if (!onlyIfAbsent || oldValue == null)
                    e.value = value;
                afterNodeAccess(e);
                return oldValue;
            }
        }
        
        ++modCount;

        //bucket超過負載因子*0.75,進行resize()操作
        if (++size > threshold)
            resize();
        afterNodeInsertion(evict);
        return null;
    }

判斷新元素和已有元素,如果沒碰撞直接放到bucket裏;如果碰撞了,以鏈表的形式存在buckets後;如果碰撞導致鏈表過長(大於等於TREEIFY_THRESHOLD),就把鏈表轉換成紅黑樹;如果節點已經存在就替換old value(保證key的唯一性);如果bucket滿了(超過load factor*current capacity),就要resize。

 

HashMap的resize方法

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

        //節點存在,舊容量>0
        if (oldCap > 0) {
            //舊的容量>=最大默認容量,把最大容量賦值給最大默認容量
            if (oldCap >= MAXIMUM_CAPACITY) {
                threshold = Integer.MAX_VALUE;
                return oldTab;
            }
            //舊容量大小在初始容量和最大容量之間,則容量擴增爲原來的2倍+1
            else if ((newCap = oldCap << 1) < MAXIMUM_CAPACITY &&
                     oldCap >= DEFAULT_INITIAL_CAPACITY)
                newThr = oldThr << 1; // double threshold
        }

        //舊threshold>0
        else if (oldThr > 0) // initial capacity was placed in threshold
            newCap = oldThr;

        //節點不存在,capacity和threshold賦默認值
        else {               // zero initial threshold signifies using defaults
            newCap = DEFAULT_INITIAL_CAPACITY;
            newThr = (int)(DEFAULT_LOAD_FACTOR * DEFAULT_INITIAL_CAPACITY);
        }
        

        //計算resize值的上限
        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) {
            //把每個bucket移動到新的bucket中
            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 { 
                        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;
                            }
                            //原索引+oldCap位置的值
                            else {
                                if (hiTail == null)
                                    hiHead = e;
                                else
                                    hiTail.next = e;
                                hiTail = e;
                            }
                        } while ((e = next) != null);

                        //原索引放到bucket裏面
                        if (loTail != null) {
                            loTail.next = null;
                            newTab[j] = loHead;
                        }
                        
                        //原索引+oldCap位置放到bucket裏面
                        if (hiTail != null) {
                            hiTail.next = null;
                            newTab[j + oldCap] = hiHead;
                        }
                    }
                }
            }
        }
        return newTab;
    }

1.如果  舊容量>最大默認容量,則舊容量=默認容量;

2.如果  初始默認容量<舊容量<最大默認容量,則舊容量=舊容量<<1;

對於原來的舊數據,如果hash值&oldCap==0,則不需要改變;如果不等於0,則需要移動到  原位置+oldCap;

例如:

假設原key的hash值二進制爲 0100110 ,

map初始容量16,  二進制爲    0010000 , &操作結果爲0,證明原來後5位小於等於15,這些元素是不需要移動位置的。如果&操作爲16,則說明舊數據可以移動到16+原位置。

3.如果  舊容量==0,則默認容量爲16,threshold=12;

 

HashMap的containsKey方法

containsKey的核心實現跟get一樣,都是去HashMap中查找是否有這個值,只是containsKey返回Boolean類型,get返回value值。

    /**
     * Returns <tt>true</tt> if this map contains a mapping for the
     * specified key.
     *
     * @param   key   The key whose presence in this map is to be tested
     * @return <tt>true</tt> if this map contains a mapping for the specified
     * key.
     */
    public boolean containsKey(Object key) {
        return getNode(hash(key), key) != null;
    }


    /**
     * Implements Map.get and related methods
     *
     * @param hash hash for key
     * @param key the key
     * @return the node, or null if none
     */
    final Node<K,V> getNode(int hash, Object key) {
        Node<K,V>[] tab; Node<K,V> first, e; int n; K k;

        //判斷hashcode跟bucket做與運算,是否有值
        if ((tab = table) != null && (n = tab.length) > 0 &&
            (first = tab[(n - 1) & hash]) != null) {

            //如果key的hash值跟第一個元素的hash值相等,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) {

                //通過樹查找
                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;
    }

1.key的hash值跟原始容量-1做&運算,確定桶的位置

2.如果直接命中,則返回,時間複雜度爲O(1);否則,如果是樹,進行樹節點的查找,時間複雜度爲O(logn);如果是鏈表,進行鏈表的循環查找,時間複雜度爲O(n)。

 

 

參考資料:

JDK1.8HashMap源碼

Java HashMap工作原理及實現

紅黑樹

 

 

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