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.
        将指定的 key 与 value 相关联。
        如果在 map 中指定的 key 存在了,则旧的 value 将被替换
     *
     * @param key key with which the specified value is to be associated
                键,与指定的 value 进行关联
     * @param value value to be associated with the specified key
                值,与指定的 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) {
        // hash(Object key) 简单来说,通过 key 的 hashCode 进行计算碰撞较少的散列值。若 key 为 null 则返回 0,只允许 key 存在一个 null。
        return putVal(hash(key), key, value, false, true);
    }

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


    /**
     * Implements Map.put and related methods
       实现了 Map.put 及相关方法(例:扩容)。
     *
     * @param hash hash for key
                key 的 hash 散列值                  
     * @param key the key
                要进行关联的 key
     * @param value the value to put
                要进行关联的 value
     * @param onlyIfAbsent if true, don't change existing value
                onlyIfAbsent 如果为 true 则不变更现有值(在 table 数组的 "(n - 1) & hash" 下标时,其标志会起到作用。注: n 为数组中数量)
     * @param evict if false, the table is in creation mode.
                evict  如果为 false 则表处于创建模式
     * @return previous value, or null if none
                前一个值如果没有则为 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;
        // 如果 table 为 null 或者数量为 0 时,进行扩容
        if ((tab = table) == null || (n = tab.length) == 0)
            n = (tab = resize()).length;
        // 如果 hash 对应的下标为 null ,则直接新建 Node 即可
        if ((p = tab[i = (n - 1) & hash]) == null)
            tab[i] = newNode(hash, key, value, null);
        else {
            Node<K,V> e; K k;
            // 如果传入的 key hash 值等于对应的下标值的 hash ,并且 key 也相等(== 基本类型比较、栈的引用类型指针比较 或 equals 值比较相等)时,则将值替换掉
            if (p.hash == hash &&
                ((k = p.key) == key || (key != null && key.equals(k))))
                e = p;
            // 如果对应的下标值为红黑树时,则将 hash key value 添加到红黑树尾部
            else if (p instanceof TreeNode)
                e = ((TreeNode<K,V>)p).putTreeVal(this, tab, hash, key, value);
            else {
                // 如果以上都不是,那么就是 Node 链表结构了
                for (int binCount = 0; ; ++binCount) {
                    //如果遍历到空时,代表已经到了尾部了,我们只需要将链式的尾巴设置为新的 Node 对象即可
                    if ((e = p.next) == null) {
                        //新建 Node 对象,且与最后一个对象进行关联,这里也是线程不安全的一个点,因为多个线程同时运行时,虽然你的尾巴加上了,但在继续运行的过程中会被别的线程替换掉,或者说自己可能替换掉别人的。
                        p.next = newNode(hash, key, value, null);
                        // 当循环次数大于等于 8 时,会将链表转为红黑树。注:链表不过超过 8 的,因为超过 8 的已经成了红黑树,下次进来都不会走这里了。
                        if (binCount >= TREEIFY_THRESHOLD - 1) // -1 for 1st
                            //转红黑树,可以关注下这个方法,只有当 table 数组大小大于等于 64 时,才会转为红黑树,不然就会进行扩容。
                            treeifyBin(tab, hash);
                        break;
                    }
                    //如果传入 key hash 与链表中值一样时,则替换 value 值
                    if (e.hash == hash &&
                        ((k = e.key) == key || (key != null && key.equals(k))))
                        break;
                    //将当前 e 赋值给 p,开始新的一轮链式循环
                    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;
        //size 为 key-value 存在的数量,超过阈值时,则进行扩容
        if (++size > threshold)
            resize();
        afterNodeInsertion(evict);
        return null;
    }


    /**
     * Replaces all linked nodes in bin at index for given hash unless
     * table is too small, in which case resizes instead.
     */
    final void treeifyBin(Node<K,V>[] tab, int hash) {
        int n, index; Node<K,V> e;
        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);
        }
    }

*源码中有很多值得看的点,但我们每次只用关注自己有兴趣、对自己思维有帮助的点即可,不然关注多个点反而容易混乱。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值