HashMap

本文深入探讨HashMap的put方法和get方法。对于put方法,分析了长度大于8时转换为红黑树的原因,旨在优化插入效率。而对于get方法,讨论了HashMap的线程安全性,指出其在高并发环境下可能引发的问题。

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

一.put方法

    public V put(K key, V value) {
        return putVal(hash(key), key, value, false, true);
    }

    //根据key计算hash值
    static final int hash(Object key) {
        int h;
        return (key == null) ? 0 : (h = key.hashCode()) ^ (h >>> 16);
    }

    final V putVal(int hash, K key, V value, boolean onlyIfAbsent,boolean evict) {
        //初始化空数组 Node<K,V>[] 和一个空节点 Node<K,V> p
        Node<K,V>[] tab; Node<K,V> p; int n, i;

        //判断当前这个数组是否为空,如果为空,则初始化一个长度为16的数组。
        if ((tab = table) == null || (n = tab.length) == 0)
            n = (tab = resize()).length; //n=8

        //根据hash值去数组里面取Node<K,V> p,如果p为空,那么就newNode放入这个位置
        if ((p = tab[i = (n - 1) & hash]) == null)
            tab[i] = newNode(hash, key, value, null);
        else {
            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)
                //如果p是红黑树,那直接在树上新增节点
                e = ((TreeNode<K,V>)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);
                        //如果链表这个长度大于等于8,则将其转化为一颗红黑树
                        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;
        //如果当前数组被使用的长度 > 数组总长度的0.75倍,则扩容,扩容2倍。
        if (++size > threshold)
            resize();
        afterNodeInsertion(evict);
        return null;
    }

思考:

1.为什么长度大于8之后要将链表变为红黑树?红黑树插入,删除,遍历最差的时间复杂度都是logN,但是比较占用空间(TreeNodes的大小是常规Nodes的两倍),只有桶中有足够多的元素时,才有必要使用树。根据官方文档,桶的长度超过8的概率非常非常小。所以作者应该是根据概率统计而选择了8作为阀值。

2.为什么每次扩容要扩容为之前长度的两倍?元素分布更均匀,减少hash碰撞;

二.get方法

    public V get(Object key) {
        Node<K,V> e;
        return (e = getNode(hash(key), key)) == null ? null : e.value;
    }
    final Node<K,V> getNode(int hash, Object key) {
        Node<K,V>[] tab; Node<K,V> first, e; int n; K k;
        //对数组进行判空
        if ((tab = table) != null && (n = tab.length) > 0 &&
            (first = tab[(n - 1) & hash]) != null) {
            //如果hash值相等,且key相等,则返回这个元素
            if (first.hash == hash && // always check first node
                ((k = first.key) == key || (key != null && key.equals(k))))
                return first;
            //如果不符合上述条件,则判断是否是个树
            if ((e = first.next) != null) {
                //如果是树,getTreeNode遍历树获取节点
                if (first instanceof TreeNode)
                    return ((TreeNode<K,V>)first).getTreeNode(hash, key);
                //循环链表,获取hash值相等且key相等的元素返回
                do {
                    if (e.hash == hash &&
                        ((k = e.key) == key || (key != null && key.equals(k))))
                        return e;
                } while ((e = e.next) != null);
            }
        }
        return null;
    }

思考:

1.hashMap是线程安全的吗?是否可以被用于高并发场景?非线程安全,主要是因为resize()里面的Rehash,在高并发场景下有可能造成环形链表。

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值