HashMap-put剖析

前言

作为一个java开发,我们在代码编程中经常会用到 k-v 键值对类型的容器,而其最常用到的即咱们的 HashMap。

首先,HashMap是什么呢,大家熟知,HashMap是基于哈希表的Map接口的非同步实现,它允许null键和null值,且HashMap依托于它的数据结构的设计,存储效率特别高,所以被咱们常用。

HashMap里面采用的数据结构有:数组+单向链表+双向链表+红黑树,不愧是大佬们写的容器类,一个字,牛!

这篇文章咱们就来剖析下 HashMap 的 put 操作,看看往 HashMap 里面塞数据的时候会经过哪些逻辑。

注:本文基于Jdk1.8!

代码剖析
put 方法

这是 HashMap 做 put 操作的入口方法

public V put(K key, V value) {
    // 调用putVal方法
    return putVal(hash(key), key, value, false, true);
}
putVal 方法

这是 HashMap 塞数据实际的逻辑代码方法

/**
 * 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<K,V>[] tab; Node<K,V> p; int n, i;
    // 判断元素是不是空了,是的话就resize
    if ((tab = table) == null || (n = tab.length) == 0)
        n = (tab = resize()).length;
    // 找到了这个hash值所在的链表位置,并发现是空的,创建新链表节点,并放进链表数组
    if ((p = tab[i = (n - 1) & hash]) == null)
        tab[i] = newNode(hash, key, value, null);
    else {
        Node<K,V> e; K k;
        // 找到了这个hash值所在的链表,且相中了连key也是相同的,则直接进行覆盖
        if (p.hash == hash &&
            ((k = p.key) == key || (key != null && key.equals(k))))
            e = p;
        // 如果这个hash值所在的链表已经是红黑树,则投进去
        else if (p instanceof TreeNode)
            e = ((TreeNode<K,V>)p).putTreeVal(this, tab, hash, key, value);
        else {
            // 遍历这个hash值所在的链表,从头到尾寻找相中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;
                }
                // 找到了这个hash值所在的链表,且相中了连key也是相同的,则直接进行覆盖
                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;
    // 数量达到了阈值,则需要resize
    if (++size > threshold)
        resize();
    // 执行节点插入后的动作,如果有实现逻辑的话
    afterNodeInsertion(evict);
    return null;
}
treeifyBin 方法

这是 HashMap 进行链表转换判断及操作的逻辑代码方法

/**
 * Replaces all linked nodes in bin at index for given hash unless
 * table is too small, in which case resizes instead.
 * 替换给定哈希的索引处bin中的所有链接节点,除非表太小,在这种情况下会调整大小。
 */
final void treeifyBin(Node<K,V>[] tab, int hash) {
    int n, index; Node<K,V> e;
    // 链表数组是null,或者其数量小于64,则进行resize操作
    if (tab == null || (n = tab.length) < MIN_TREEIFY_CAPACITY)
        resize();
    else if ((e = tab[index = (n - 1) & hash]) != null) {
        // 当这个hash索引处的链表不是null的时候进行才以下逻辑操作
        TreeNode<K,V> hd = null, tl = null;
        do {
            // 先将该链表转换成双向链表,Node<K,V>变成
            // TreeNode<K,V> replacementTreeNode(Node<K,V> p, Node<K,V> next) {
            //     return new TreeNode<>(p.hash, p.key, p.value, next);
            // }
            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);
        // 将转换的双向链表放进链表数组
        // 然后进行转换成红黑树
        // /**
        // * Forms tree of the nodes linked from this node.
        // * @return root of tree
        // */
        // final void treeify(Node<K,V>[] tab) {...}
        if ((tab[index] = hd) != null)
            hd.treeify(tab);
    }
}
结语

到此,对 HashMap 的 put 方法代码剖析就告一段落了,学习无止境,技术的路上,期待和您一起交流!

如果您看到了这里,欢迎和我沟通交流!
             一个95后码农

个人博客:fy-blog

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值