6、JDK1.8HashMap源码分析系列文章(putVal)

目录

1、put(K key, V value)

2、putIfAbsent(K key, V value)

3、putVal(int hash, K key, V value, boolean onlyIfAbsent, boolean evict)

4、newNode(int hash, K key, V value, Node next),v>

5、putTreeVal(HashMap map, Node[] tab, int h, K k, V v),v>,v>

6、treeifyBin(Node[] tab, int hash),v>

7、afterNodeAccess(Node p),v>

8、afterNodeInsertion(boolean evict)

9、comparableClassFor(Object x)

10、compareComparables(Class kc, Object k, Object x)

11、tieBreakOrder(Object a, Object b)

12、newTreeNode(int hash, K key, V value, Node next),v>

13、moveRootToFront(Node[] tab, TreeNode root),v>,v>

14、balanceInsertion(TreeNode root, TreeNode x),v>,v>


 

1、put(K key, V value)

        /**
         * @param key   key值
         * @param value value值
         * @return V 返回修改前的值,如果没有就返回null
         * @Author muyi
         * @Date 13:55 2020/8/4
         */
        public V put(K key, V value) {
            return putVal(hash(key), key, value, false, true);
        }

2、putIfAbsent(K key, V value)

        /**
         * 与put相同,区别在于,如果key存在,不修改其对应的value值
         *
         * @param key
         * @param value
         * @return V
         * @Author muyi
         * @Date 14:02 2020/8/4
         */
        @Override
        public V putIfAbsent(K key, V value) {
            return putVal(hash(key), key, value, true, true);
        }

3、putVal(int hash, K key, V value, boolean onlyIfAbsent, boolean evict)

        /**
         *
         * @param  hash: key经过哈希算法之后获得的值
         * @param key: 储存到HashMap的key
         * @param value: 储存到HashMap的key对应的value
         * @param onlyIfAbsent: 如果包含了该key,则不更新对应的值,众所周知,put()除了新增之外,还有更新的功能,是因为put()调用putVal()时候传的都是false
         * @param evict: HashMap是否处于创建模式,false则是处于创建模式,ture则相反
         * @return V 返回修改前的值
         * @Author muyi
         * @Date 11:16 2020/8/3
         */
        final V putVal(int hash, K key, V value, boolean onlyIfAbsent,
                       boolean evict) {
            // tab-桶数组,p-hash值对应的桶数组索引位置的元素
            HashMap.Node<K, V>[] tab;
            HashMap.Node<K, V> p;
            // n-桶数组的长度,i-索引值
            int n, i;
            // 如果桶数组不存在,或者桶的长度等于0,需要对桶数组进行扩容
            if ((tab = table) == null || (n = tab.length) == 0)
                n = (tab = resize()).length;

            if ((p = tab[i = (n - 1) & hash]) == null)
                // 如果hash值对应的桶数组索引值为null,说明该位置没有任何元素,直接新建一个普通节点,将钙元素赋予当前位置即可
                tab[i] = newNode(hash, key, value, null);
            else {
                // e-临时节点值,用于存放当前hash值对应桶位置的节点元素
                HashMap.Node<K, V> e;
                // k-hash值对应桶位置元素的key
                K k;
                /**
                 * 两个条件与:
                 * 1、p.hash == hash:hash值相等,(在对节点进行实例化的时候,内部存放的hash即使key的hash值,故这里直接这样判断)
                 * 2、((k = p.key) == key || (key != null && key.equals(k))):key对应的地址相等或者值相等
                 * 当这两个条件满足时,说明key值相等
                 */
                if (p.hash == hash &&
                        ((k = p.key) == key || (key != null && key.equals(k))))
                    e = p;
                    // 如果key值不相等且该位置的元素是一个树形节点,直接把当前值放到树形结构中,否则以链表的形式存储
                else if (p instanceof HashMap.TreeNode)
                    e = ((HashMap.TreeNode<K, V>) p).putTreeVal(this, tab, hash, key, value);
                else {
                    // 如果key值不相等且该节点也不是一个树形节点,对当前位置的链表元素进行遍历,直到将当前元素放置到链表末尾(尾插发,与1.7的头插法有点区别)
                    for (int binCount = 0; ; ++binCount) {
                        // 将当前元素放置到当前位置链表的尾节点
                        if ((e = p.next) == null) {
                            p.next = newNode(hash, key, value, null);
                            // binCount从0 开始计数,当 binCount >= 7 时需要对该位置的链表进行判断,是否需要进行元素树化
                            if (binCount >= TREEIFY_THRESHOLD - 1)
                                treeifyBin(tab, hash);
                            // 元素放置成功,直接跳出当前循环
                            break;
                        }
                        /**
                         * 1、e.hash == hash (在对节点进行实例化的时候,内部存放的hash即使key的hash值,故这里直接这样判断)
                         * 2、((k = e.key) == key || (key != null && key.equals(k)))
                         * 判断hash和key值是否相等,如果相等,说明已找到key值对应的元素
                         */
                        if (e.hash == hash &&
                                ((k = e.key) == key || (key != null && key.equals(k))))
                            break;
                        // 相当于 p=p.next,遍历指针前移,因为在前面有e = p.next。
                        p = e;
                    }
                }
                if (e != null) {
                    // 获取当前位置已经存在的值
                    V oldValue = e.value;
                    /**
                     * 1、onlyIfAbsent true-如果key对应的value存在则不修改,false-对存在的value值进行修改
                     *    如果onlyIfAbsent为false,无论旧值是否存在都需要对值进行修改
                     * 2、如果onlyIfAbsent为true,只有旧值为为null的时候才能为kery对应的值进行修改
                     */
                    if (!onlyIfAbsent || oldValue == null)
                        e.value = value;
                    // ConcurrentHashMap使用的方法,这里未使用,详见ConcurrentHashMap源码
                    afterNodeAccess(e);
                    return oldValue;
                }
            }
            /**
             * 对修改次数值进行累加
             * Fail-Fast 机制:java.util.HashMap 不是线程安全的,因此如果在使用迭代器的过程中有其他线程修改了map,
             * 那么将抛出ConcurrentModificationException,这就是所谓fail-fast策略。这一策略在源码中的实现是通过 modCount 域,
             * modCount 顾名思义就是修改次数,对HashMap 内容的修改都将增加这个值,那么在迭代器初始化过程中会将这个值赋给迭代器的 expectedModCount。
             * 在迭代过程中,判断 modCount 跟 expectedModCount 是否相等,如果不相等就表示已经有其他线程修改了 Map:注意到 modCount 声明为 volatile,
             * 保证线程之间修改的可见性。
             */
            ++modCount;
            // 对size值进行修改,如果长度大于扩容阈值,需要对桶数组进行扩容
            if (++size > threshold)
                resize();
            // ConcurrentHashMap使用的方法,这里未使用,详见ConcurrentHashMap源码
            afterNodeInsertion(evict);
            return null;
        }

4、newNode(int hash, K key, V value, Node<K,V> next)

        /**
         * HashMap.Node类的构造方法,创建一个新的普通节点
         *
         * @param hash  key对应的hash值
         * @param key   key
         * @param value value
         * @param next  后继节点
         * @Author muyi
         * @Date 14:08 2020/8/4
         */
        HashMap.Node<K, V> newNode(int hash, K key, V value, HashMap.Node<K, V> next) {
            return new HashMap.Node<>(hash, key, value, next);
        }

5、putTreeVal(HashMap<K,V> map, Node<K,V>[] tab, int h, K k, V v)

        /**
         * @param map 当前map
         * @param tab 当前map下存放数据的桶数组
         * @param h   key对应的hash值
         * @param k   key
         * @param v   value
         * @return com.example.bd.javaee.hashmap.HashMap.TreeNode<K, V>
         * @Author muyi
         * @Date 12:03 2020/8/3
         */
        final HashMap.TreeNode<K, V> putTreeVal(HashMap<K, V> map, HashMap.Node<K, V>[] tab,
                                                int h, K k, V v) {
            // kc-实现了Comparable接口的class,searched-标记是否被搜索过
            Class<?> kc = null;
            boolean searched = false;
            // 获取根节点
            HashMap.TreeNode<K, V> root = (parent != null) ? root() : this;
            // 遍历红黑树
            for (HashMap.TreeNode<K, V> p = root; ; ) {
                // dir-当前节点是放在树的左子树还是右子树的标志,ph-遍历过程中当前节点key所对应的hash值,pk-遍历过程中当前节点的key值
                int dir, ph;
                K pk;
                // 小于等于左子树,大于右子树
                if ((ph = p.hash) > h)
                    dir = -1;
                else if (ph < h)
                    dir = 1;
                    // 如果相等,说明已找到key值相同的元素,直接返回找的节点
                else if ((pk = p.key) == k || (k != null && k.equals(pk)))
                    return p;
                /**
                 * 以下两个条件是或的关系
                 * 1、(kc == null && (kc = comparableClassFor(k)) == null)
                 * 返回当前节点key值实现了Comparable接口的class
                 * 2、dir = compareComparables(kc, k, pk)) == 0
                 * 比较当前节点和遍历节点的key值大小
                 * 当第一个条件为true,那么不会执行第二个条件,并直接执行 dir = tieBreakOrder(k, pk);
                 * 即只有kc不等于null的时候,才会调用compareComparables()方法
                 */
                else if ((kc == null &&
                        (kc = comparableClassFor(k)) == null) ||
                        (dir = compareComparables(kc, k, pk)) == 0) {
                    // 如果已经通过Comparable方法比较过大小了,还是没有找到,那么就只有通过默认hashCode方法来进行绝对比较了
                    if (!searched) {
                        HashMap.TreeNode<K, V> q, ch;
                        // 查找过标记位置true
                        searched = true;
                        /**
                         * 以下两个条件或
                         * 1、(ch = p.left) != null && (q = ch.find(h, k, kc)) != null)
                         * 遍历节点的左孩子不为空,并且在左孩子中找到了不为空的节点,
                         * 2、((ch = p.right) != null && (q = ch.find(h, k, kc)) != null)
                         * 遍历节点的左孩子不为空,并且在左孩子中找到了不为空的节点,
                         */
                        if (((ch = p.left) != null &&
                                (q = ch.find(h, k, kc)) != null) ||
                                ((ch = p.right) != null &&
                                        (q = ch.find(h, k, kc)) != null))
                            // 找到了节点直接返回
                            return q;
                    }
                    // 比较当前节点key值和遍历节点key值的大小
                    dir = tieBreakOrder(k, pk);
                }

                // key值对应的数据未找到
                HashMap.TreeNode<K, V> xp = p;
                if ((p = (dir <= 0) ? p.left : p.right) == null) {
                    HashMap.Node<K, V> xpn = xp.next;
                    // 生成一个树节点
                    HashMap.TreeNode<K, V> x = map.newTreeNode(h, k, v, xpn);
                    if (dir <= 0)
                        xp.left = x;
                    else
                        xp.right = x;
                    xp.next = x;
                    x.parent = x.prev = xp;
                    if (xpn != null)
                        ((HashMap.TreeNode<K, V>) xpn).prev = x;
                    moveRootToFront(tab, balanceInsertion(root, x));
                    return null;
                }
            }
        }

6、treeifyBin(Node<K,V>[] tab, int hash)

详见JDK1.8HashMap源码分析系列文章(treeifyBin,treeify)

7、afterNodeAccess(Node<K,V> p)

8、afterNodeInsertion(boolean evict)

9、comparableClassFor(Object x)

详见JDK1.8HashMap源码分析系列文章(comparableClassFor、compareComparables、tieBreakOrder)

10、compareComparables(Class<?> kc, Object k, Object x)

详见JDK1.8HashMap源码分析系列文章(comparableClassFor、compareComparables、tieBreakOrder)

11、tieBreakOrder(Object a, Object b)

详见JDK1.8HashMap源码分析系列文章(comparableClassFor、compareComparables、tieBreakOrder)

12、newTreeNode(int hash, K key, V value, Node<K,V> next)

        /**
         * 根据node节点生成一个红黑树节点
         *
         * @param hash  key对应的hash值
         * @param key   key
         * @param value value
         * @param next  后继节点
         * @return com.example.bd.javaee.hashmap.HashMap.TreeNode<K, V>
         * @Author muyi
         * @Date 14:16 2020/8/4
         */
        HashMap.TreeNode<K, V> newTreeNode(int hash, K key, V value, HashMap.Node<K, V> next) {
            return new HashMap.TreeNode<>(hash, key, value, next);
        }

13、moveRootToFront(Node<K,V>[] tab, TreeNode<K,V> root)

详见JDK1.8HashMap源码分析系列文章(moveRootToFront、checkInvariants)

14、balanceInsertion(TreeNode<K,V> root, TreeNode<K,V> x)

详见JDK1.8HashMap源码分析系列文章(moveRootToFront、checkInvariants)

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值