HashMap源码阅读笔记 put(K key, V value)实现

先说下众所周知的结论吧,HashMap是个数组加链表(或树)的形式。

  • 先来看下类图吧。
    类图
    从类图可以看到,HashMap继承于AbstractMap,实现了Map、Cloneable、java.io.Serializable接口的。
  • 重要字段。
	/**
     * 在第一次使用的时候初始化 自动扩容。当重新分配大小时,其长度总会是2的倍数
     */
    transient Node<K,V>[] table;

    /**
     * 缓存entrySet,被{@link #keySet()}和{@link #values()} 调用
     */
    transient Set<Map.Entry<K,V>> entrySet;

    /**
     * 保存元素数量
     */
    transient int size;

    /**
     * 结构至今为止被成功更改次数。
     * 指修改Mapping数目或者进行rehash操作。
     * 即,修改已经存在节点不会导致此值进行修改。
     * 如果在进行一次操作时前后不一致将抛出{@link ConcurrentModificationException}
     */
    transient int modCount;

    /**
     * 下一次进行resize的目标值
     * @serial
     */
    int threshold;

    /**
     * 负载因子
     * @serial
     */
    final float loadFactor;
  • put(K key, V value)定义
   /**
     * 放置新对象到Map中。如果存在同样的key值,那么旧值将被覆盖
     * 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);
    }

我们可以看到其实put方法是调用了putVal方法的。并且如果我们定义的key已经存在的话,它同时会旧的value给我们。
那么putVal方法又是如何实现的呢?

/**
     * 实现Map的put及相关方法
     * 快速返回请点击
     * @see #get(Object)
     * 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  为true则不更改已经存在的key
     * @param evict if false, the table is in creation mode.
     * @return previous value, or null if none
     * @see #get(Object)
     */
    final V putVal(int hash, K key, V value, boolean onlyIfAbsent, boolean evict) {
        //数组
        Node<K,V>[] tab;
        //当前元素
        Node<K,V> p;
        // n 数组长度
        int n, i;
        //复制tab元素,并将当前tab长度赋值给n
        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 {
            //如果节点不为空 说明此位置已存在链表(数)需要挂载到后面
            // e existing mapping for key ;k 用于获取当前循环k
            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 {
                //非头结点且为链表 循环链表验证是否是已经存在的key
                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)))){
                        //链表中存在对应的key
                        break;
                    }
                    p = e;
                }
            }

            if (e != null) { // existing mapping for key  存在相同key情况处理
                V oldValue = e.value;
                if (!onlyIfAbsent || oldValue == null){
                    //更改当前key对应的值
                    e.value = value;
                }
                afterNodeAccess(e);
                return oldValue;
            }
        }

        //完成新增操作后更新被修改次数
        ++modCount;
        //大于负载后进行扩容
        if (++size > threshold){
            resize();
        }
        afterNodeInsertion(evict);
        return null;
    }

注意: putVal方法仅在新增Mapping的情况下修改了modCount,因为修改原有key对应的Value是不涉及对结构的更改的。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值