资讯专栏INFORMATION COLUMN

Java 8 HashMap中的TreeNode.putTreeVal方法分析

AJie / 2433人阅读

摘要:考虑两大情况,已经存在这个红黑树中当中了,就直接放回对应的那个节点从红黑树的节点开始遍历,定位到要插入的叶子节点,插入新节点除了要维护红黑树的平衡外可以参考源码,还需要维护节点之间的前后关系,这里似乎同时是在维护双向链表关系。

举例一个入口,利用一个Map构造HashMap时

    /**
     * Constructs a new HashMap with the same mappings as the
     * specified Map.  The HashMap is created with
     * default load factor (0.75) and an initial capacity sufficient to
     * hold the mappings in the specified Map.
     *
     * @param   m the map whose mappings are to be placed in this map
     * @throws  NullPointerException if the specified map is null
     */
    public HashMap(Map m) {
        this.loadFactor = DEFAULT_LOAD_FACTOR;
        putMapEntries(m, false);
    }

然后就是调用putMapEntries方法,第二个参数其实可以看作细节,个人认为它和HashMap的子类LinkedHashMap有关,evict是逐出的意思,如果基于LinkedHashMap实现LRU缓存的话,这个evict参数正好就用上了。

    /**
     * Implements Map.putAll and Map constructor
     *
     * @param m the map
     * @param evict false when initially constructing this map, else
     * true (relayed to method afterNodeInsertion).
     */
    final void putMapEntries(Map m, boolean evict) {
        int s = m.size();
        if (s > 0) {
            if (table == null) { // pre-size
                float ft = ((float)s / loadFactor) + 1.0F;
                int t = ((ft < (float)MAXIMUM_CAPACITY) ?
                         (int)ft : MAXIMUM_CAPACITY);
                if (t > threshold)
                    threshold = tableSizeFor(t);
            }
            else if (s > threshold)
                resize();
            for (Map.Entry e : m.entrySet()) {
                K key = e.getKey();
                V value = e.getValue();
                putVal(hash(key), key, value, false, evict);
            }
        }
    }

可以看到在for循环中遍历旧的entrySet视图,然后将一个个的key-value对放入新构造的HashMap中,

            for (Map.Entry e : m.entrySet()) {
                K key = e.getKey();
                V value = e.getValue();
                putVal(hash(key), key, value, false, evict);
            }

展开putVal(hash(key), key, value, false, evict);

    /**
     * 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[] tab; Node p; int n, i;
        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 {
            Node 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)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) { // existing mapping for key
                V oldValue = e.value;
                if (!onlyIfAbsent || oldValue == null)
                    e.value = value;
                afterNodeAccess(e);
                return oldValue;
            }
        }
        ++modCount;
        if (++size > threshold)
            resize();
        afterNodeInsertion(evict);
        return null;
    }

通过hash(key)定位到HashMap中tab数组的索引,如果这个数组元素的头节点正好是TreeNode类型,那么就将执行

e = ((TreeNode)p).putTreeVal(this, tab, hash, key, value);

此时this是HashMap自身。
putTreeVal考虑两大情况,
1)key已经存在这个红黑树中当中了,就直接放回对应的那个节点;
2)从红黑树的root节点开始遍历,定位到要插入的叶子节点,插入新节点;
putTreeVal除了要维护红黑树的平衡外(可以参考TreeMap源码),还需要维护节点之间的前后关系,这里似乎同时是在维护双向链表关系。

        /**
         * Tree version of putVal.
         */
        final TreeNode putTreeVal(HashMap map, Node[] tab,
                                       int h, K k, V v) {
            Class kc = null;
            boolean searched = false;
            TreeNode root = (parent != null) ? root() : this;
            for (TreeNode p = root;;) {
                int dir, ph; K pk;
                if ((ph = p.hash) > h)
                    dir = -1;
                else if (ph < h)
                    dir = 1;
                else if ((pk = p.key) == k || (k != null && k.equals(pk)))
                    return p;
                else if ((kc == null &&
                          (kc = comparableClassFor(k)) == null) ||
                         (dir = compareComparables(kc, k, pk)) == 0) {
                    if (!searched) {
                        TreeNode q, ch;
                        searched = true;
                        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;
                    }
                    dir = tieBreakOrder(k, pk);
                }

                TreeNode xp = p;
                if ((p = (dir <= 0) ? p.left : p.right) == null) {
                    Node xpn = xp.next;
                    TreeNode 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)
                        ((TreeNode)xpn).prev = x;
                    moveRootToFront(tab, balanceInsertion(root, x));
                    return null;
                }
            }
        }

下面重点分析putTreeVal方法
1 首先找到root节点,

TreeNode root = (parent != null) ? root() : this;

这里的this是指TreeNode自己,从某个节点一直往上溯,直到parent==null的情况
2 递归遍历root
判断节点之间的hash大小,如果hash值相等采用key比较等
然后采用左子树或者右子树,继续遍历
(关于key值大小的比较算是细节的地方,这里暂且代入String类型的key解读源码以图整体思路流畅)
3 如果遍历到了叶子节点
比如上一步采用左子树,而左子树刚好是叶子节点,p == null
此时递归遍历结束

                if ((p = (dir <= 0) ? p.left : p.right) == null) {
                    Node xpn = xp.next;
                    TreeNode 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)
                        ((TreeNode)xpn).prev = x;
                    moveRootToFront(tab, balanceInsertion(root, x));
                    return null;
                }

xp是叶子节点的父节点,这个节点不是null,叶子节点p一定是null
新增一个节点x,next指向原来父节点的.next,x就是新增的叶子节点
1) 处理红黑树的关系
父节点xp和叶子节点x的关系,落在左子树还是右子树;
x的parent指向父节点xp x.parent = xp
最后保持红黑树平衡
2)处理双向链表的关系
类似于在xp-->xpn(xp.next)中间插入新的节点x,

x = map.newTreeNode(h, k, v, xpn);
x.prev = xp
//如果xpn不是null,则处理xpn的prev
((TreeNode)xpn).prev = x;

图示

3) 保持红黑树平衡

moveRootToFront(tab, balanceInsertion(root, x));

文章版权归作者所有,未经允许请勿转载,若此文章存在违规行为,您可以联系管理员删除。

转载请注明本文地址:https://www.ucloud.cn/yun/71407.html

相关文章

  • [学习笔记-Java集合-4] Map - HashMap源码分析

    摘要:存储结构在中,的实现采用了数组链表红黑树的复杂结构,数组的一个元素又称作桶。当一个链表的元素个数达到一定的数量且数组的长度达到一定的长度后,则把链表转化为红黑树,从而提高效率。 简介 HashMap采用key/value存储结构,每个key对应唯一的value,查询和修改的速度都很快,能达到O(1)的平均时间复杂度。它是非线程安全的,且不保证元素存储的顺序; 继承体系 showImg(...

    wing324 评论0 收藏0
  • java源码一带一路系列】之HashMap.putVal()

    摘要:表示该类本身不可比表示与对应的之间不可比。当数目满足时,链表将转为红黑树结构,否则继续扩容。至此,插入告一段落。当超出时,哈希表将会即内部数据结构重建至大约两倍。要注意的是使用许多有这相同的键值肯定会降低哈希表性能。 回顾上期✈观光线路图:putAll() --> putMapEntries() --> tableSizeFor() --> resize() --> hash() --...

    cloud 评论0 收藏0
  • JDK源码那些事儿之并发ConcurrentHashMap上篇

    前面已经说明了HashMap以及红黑树的一些基本知识,对JDK8的HashMap也有了一定的了解,本篇就开始看看并发包下的ConcurrentHashMap,说实话,还是比较复杂的,笔者在这里也不会过多深入,源码层次上了解一些主要流程即可,清楚多线程环境下整个Map的运作过程就算是很大进步了,更细的底层部分需要时间和精力来研究,暂不深入 前言 jdk版本:1.8 JDK7中,ConcurrentH...

    Leck1e 评论0 收藏0
  • HashMap源码分析(一):JDK源码分析系列

    摘要:当一个值中要存储到的时候会根据的值来计算出他的,通过哈希来确认到数组的位置,如果发生哈希碰撞就以链表的形式存储在源码分析中解释过,但是这样如果链表过长来的话,会把这个链表转换成红黑树来存储。 正文开始 注:JDK版本为1.8 HashMap1.8和1.8之前的源码差别很大 目录 简介 数据结构 类结构 属性 构造方法 增加 删除 修改 总结 1.HashMap简介 H...

    wdzgege 评论0 收藏0
  • java源码

    摘要:集合源码解析回归基础,集合源码解析系列,持续更新和源码分析与是两个常用的操作字符串的类。这里我们从源码看下不同状态都是怎么处理的。 Java 集合深入理解:ArrayList 回归基础,Java 集合深入理解系列,持续更新~ JVM 源码分析之 System.currentTimeMillis 及 nanoTime 原理详解 JVM 源码分析之 System.currentTimeMi...

    Freeman 评论0 收藏0

发表评论

0条评论

最新活动
阅读需要支付1元查看
<