Java 8的HashMap的put方法源码分析

本文详细剖析了Java中HashMap的put方法实现原理,包括如何处理哈希冲突、链表转红黑树的过程及红黑树的平衡维护策略。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

抱着加深学习印象和记录的想法,写下这篇博客。先上源码,如下图。

HashMap的put方法调用的是putVal方法,传入的 onlyIfAbsent 默认为false;evict为true。   
/**
     * 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);
    } 



/**
     * Implements Map.put and related methods.
     *
     * @param hash hash for key Key的哈希值
     * @param key the key    
     * @param value the value to put
     * @param onlyIfAbsent if true, don't change existing value 此参数的作用是:if true,不覆盖已有的Key的Value;否则覆盖,默认是覆盖的。
     * @param evict if false, the table is in creation mode.  evict,是用于HashMap的子类LinkedHashMap的扩展,这是为了实现LRU算法而设计的,旨在evict为true时,才有可以剔除掉最近最少访问的元素。还需要结合removeEldestEntry(Map.Entry<K,V> eldest)方法使用,此方法需要重写。默认返回 false,即不会删除最老的entry。

     * @return previous value, or null if none
     */
    final V putVal(int hash, K key, V value, boolean onlyIfAbsent,
                   boolean evict) {
        Node<K,V>[] tab; Node<K,V> p; int n, i;
        if ((tab = table) == null || (n = tab.length) == 0)  // 如果Bin数组为null或长度为0
            n = (tab = resize()).length;             //resize() 方法为扩容 下面会重点分析
        if ((p = tab[i = (n - 1) & hash]) == null)   // 走到这里,说明bin数组已经初始化过
                                                     //i = (n - 1) & hash,通过bin数组长度减1&key的hash值来确定数组的下标。如数组长度16(10000 - 1 = 1111),1111&随便一个hash值,得到的 下标将会在bin数组长度范围之内。具体的位运算知识就不在这里细说了。

            tab[i] = newNode(hash, key, value, null); //得到的数组下标位置为null,直接new一个node放入。
        else {
            // 否则得到bin的数组index已经被之前的节点占用
            Node<K,V> e; K k;
            if (p.hash == hash &&
                ((k = p.key) == key || (key != null && key.equals(k)))) //如果此发生了hash碰撞和key相等或者key.equals(k),做个标记,等到后面看是否覆盖此值
                e = p;
            else if (p instanceof TreeNode)    //如果这个数组位置的节点是treeNode,就用红黑树的方法来操作。后面会重点分析红黑树。
                e = ((TreeNode<K,V>)p).putTreeVal(this, tab, hash, key, value);
            else {
//走到这里说明是普通Node,遍历链表看是否有相同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,如果链表的节点超过8个,将链表转化为红黑树
                            treeifyBin(tab, hash);  //树化,后面分析
                        break;
                    }
                    if (e.hash == hash &&
                        ((k = e.key) == key || (key != null && key.equals(k))))
                        break; //找到key相同的,跳出
                    p = e;
                }
            }
            if (e != null) { // existing mapping for key
                V oldValue = e.value;
                if (!onlyIfAbsent || oldValue == null) //如果允许覆盖或者原来的value为null,覆盖原来的value。
                    e.value = value;
                afterNodeAccess(e); //此方法是为了HashMap的子类LinkedHashMap服务,作用是为了将访问过的元素放到链尾
                return oldValue;
            }
        }
        ++modCount;
        if (++size > threshold)
            resize();  //超过了HashMap的阈值,进行扩容,扩容后面分析。
        afterNodeInsertion(evict); //此方法也是为了LinkedHashMap服务,作用是当新增一个元素时,是否需要删除掉旧的元素。
        return null;
    }
        /**
         * Tree version of putVal.
         */
        final TreeNode<K,V> putTreeVal(HashMap<K,V> map, Node<K,V>[] tab,
                                       int h, K k, V v) {
            Class<?> kc = null;
            boolean searched = false; //是否有找到key相等的一个标志
            TreeNode<K,V> root = (parent != null) ? root() : this; //找到红黑树的根节点
            for (TreeNode<K,V> p = root;;) { //遍历红黑树
                int dir, ph; K pk;
                if ((ph = p.hash) > h)  //如果要插入的节点的hash值小于当前的节点的hash值
                    dir = -1;
                else if (ph < h)   //如果要插入的节点的hash值大于当前节点的hash值
                    dir = 1;
                else if ((pk = p.key) == k || (k != null && k.equals(pk)))
                    return p;  //找到了key相等的节点,返回这个节点
                else if ((kc == null &&
                          (kc = comparableClassFor(k)) == null) ||
                         (dir = compareComparables(kc, k, pk)) == 0) { // 走到这里说明要插入的节点的hash值和当前节点的hash值相等且key不一样。此时通过hash值已无法确定下一步的遍历方向,通过判断要插入的节点的key是否实现了comparable接口,通过compare 两个key来确定是作为左节点还是右节点,如果key没有实现comparable接口或者实现了comparable接口但是两个key的class不相等,无法比较(即dir=0),进入此方法获取dir
                    if (!searched) {   //此方法体的逻辑只会在这个循环中执行一次,遍历整棵树,看是否能找到和要插入的key相等的节点。找到就返回,退出此方法。此方法稍后分析。
                        TreeNode<K,V> 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;
                    }
                    //走到这里说明还是没有找到key相同的节点,获取dir,来确定下次遍历的是左节点还是右节点或者新节点的插入位置
                    //通过class的name来得到dir,如果名字相等再通过          (System.identityHashCode(a) <= System.identityHashCode(b) ?
                     -1 : 1) 确定
                    dir = tieBreakOrder(k, pk);
                }
                //此时已经得到dir的值
                TreeNode<K,V> xp = p;
                if ((p = (dir <= 0) ? p.left : p.right) == null) { //直到遇到叶子节点,才插入
                    Node<K,V> xpn = xp.next;
                    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)
                        ((TreeNode<K,V>)xpn).prev = x;
                    moveRootToFront(tab, balanceInsertion(root, x));//这些节点即可以作为一棵树,也同时是双向链表,调整树的根节点为链表的第一个节点,也就是bin数组存的那个节点。
                    return null;
                }
            }
        }
/*当链表的个数>=8时,将链表转化为红黑树的方法。

/**
     * 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) //table is too   small,resizes instead,如果bin数组的容量小于MIN_TREEIFY_CAPACITY,扩容而不是树化

            resize();
        else if ((e = tab[index = (n - 1) & hash]) != null) { //取到链表第一个元素,遍历链表,将Node转变为TreeNode(树化)
            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) //将所有的链表Node转化为TreeNode之后,开始构造红黑树
                hd.treeify(tab);
        }
    }
        从第一个节点开始构造红黑树,红黑树规则:
        1. 每个节点不是红色就是黑色的
        2. 根节点总是黑色的
        3. 如果节点是红色的,则它的子节点必须是黑色的(反之不一定)
        4. 从根节点到叶节点或空子节点的每条路径,必须包含相同数目的黑色节点(即相同的黑色高度)
        Note:插入的节点颜色总是红色的。 
        /**
         * Forms tree of the nodes linked from this node.
         */
        final void treeify(Node<K,V>[] tab) {
            TreeNode<K,V> root = null;
            for (TreeNode<K,V> x = this, next; x != null; x = next) {
                next = (TreeNode<K,V>)x.next;
                x.left = x.right = null;
                if (root == null) { //根节点为黑色的
                    x.parent = null;
                    x.red = false;
                    root = x;
                }
                else {
                    K k = x.key;
                    int h = x.hash;
                    Class<?> kc = null;
                    for (TreeNode<K,V> p = root;;) {
                        int dir, ph;
                        K pk = p.key;
                        if ((ph = p.hash) > h) //hash值大的在右节点,小的在左节点。以下compare key的结果同理。
                            dir = -1;
                        else if (ph < h)
                            dir = 1;
                        else if ((kc == null &&
                                  (kc = comparableClassFor(k)) == null) ||
                                 (dir = compareComparables(kc, k, pk)) == 0)
                            dir = tieBreakOrder(k, pk);

                        TreeNode<K,V> xp = p;
                        if ((p = (dir <= 0) ? p.left : p.right) == null) {
                            x.parent = xp;
                            if (dir <= 0)
                                xp.left = x;
                            else
                                xp.right = x;
                            root = balanceInsertion(root, x); //插入一个节点之后,需要维护树的平衡。
                            break;
                        }
                    }
                }
            }
            moveRootToFront(tab, root);
        }
    /**
     * 涉及到红黑树的变色,左旋,右旋,还是挺复杂的,只好一点点分析了
        如果是第一次插入,由于原树为空,所以原树为空,只会违反根节点一定为黑这个规则,所以只需要把根节点涂黑;如果插入节点的父节点是黑色的,那不会违背红黑树的规则,什么也不需要做;但是以下三种情况需要变色和旋转:
        1.插入节点的父节点和其叔叔节点均为红色
        2.插入节点的父节点是红色的,叔叔节点是黑色的,且插入节点是其父节点的右子节点
        3.插入节点的父节点是红色的,叔叔节点是黑色的,且插入节点是其父节点的左子节点
     **/          
    static <K,V> TreeNode<K,V> balanceInsertion(TreeNode<K,V> root,
                                                    TreeNode<K,V> x) {
            x.red = true;
            for (TreeNode<K,V> xp, xpp, xppl, xppr;;) { //一直遍历直到符合推出条件
                if ((xp = x.parent) == null) { //如果插入的是第一个节点,那就是root节点,涂黑,返回
                    x.red = false;
                    return x;
                }
                else if (!xp.red || (xpp = xp.parent) == null) //如果父节点是黑色或父节点是根节点,直接返回根节点,不需做任何调整
                    return root;
                if (xp == (xppl = xpp.left)) { // 如果父节点是爷爷的左孩子
                    if ((xppr = xpp.right) != null && xppr.red) { //如果爷爷的右孩子是红色的,将爷爷的右孩子涂黑,将父亲涂黑,将爷爷涂红,并将当前节点指向爷爷
                        xppr.red = false;
                        xp.red = false;
                        xpp.red = true;
                        x = xpp;
                    }
                    else { //如果父亲是爷爷的右孩子
                        if (x == xp.right) { //如果当前节点是父亲的右孩子
                            root = rotateLeft(root, x = xp); //左旋
                            xpp = (xp = x.parent) == null ? null : xp.parent;
                        }
                        if (xp != null) {//父节点不为空 将父亲涂黑 爷爷涂红 进行右旋
                            xp.red = false;
                            if (xpp != null) {
                                xpp.red = true;
                                root = rotateRight(root, xpp);
                            }
                        }
                    }
                }
                else { //父亲是爷爷的右孩子
                    if (xppl != null && xppl.red) { //左叔叔是红色的
                        xppl.red = false; //左叔叔涂黑
                        xp.red = false; //父亲涂黑
                        xpp.red = true; //爷爷涂红
                        x = xpp; //当前节点指向爷爷
                    }
                    else { //左叔叔为空或为黑色的
                        if (x == xp.left) { //如果当前节点是父节点的左孩子
                            root = rotateRight(root, x = xp); //右旋
                            xpp = (xp = x.parent) == null ? null : xp.parent;
                        }
                        if (xp != null) { //如果父节点不为空,将父节点涂黑
                            xp.red = false;
                            if (xpp != null) {//爷爷不为空
                                xpp.red = true; //将爷爷涂红
                                root = rotateLeft(root, xpp); //左旋
                            }
                        }
                    }
                }
            }
        }

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值