源码分析——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工作原理及实现

红黑树

 

 

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