遍历HashMap时增删导致报错问题

本文详细解析了HashMap在Java 1.8中的源码,特别是modCount的作用和何时修改。modCount用于在迭代时检测HashMap的结构是否被修改,避免并发修改异常。在put、remove、clear等操作时,modCount会增加。遍历HashMap时进行修改操作将导致ConcurrentModificationException。

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

背景

在和朋友的一次交谈中,朋友遇到了这样一个问题:在遍历map时,做了一步remove操作,然后就发生了ConcurrentModificationException异常。由此我点进源码探究了一番。

JDK版本:1.8

探究

点进HashMap源码发现,在每次循环结束前,会校验一下modCount的值,如果modCount变了,就会抛出ConcurrentModificationException异常。

@Override
public void forEach(BiConsumer<? super K, ? super V> action) {
    Node<K,V>[] tab;
    if (action == null)
        throw new NullPointerException();
    if (size > 0 && (tab = table) != null) {
        int mc = modCount;
        for (int i = 0; i < tab.length; ++i) {
            for (Node<K,V> e = tab[i]; e != null; e = e.next)
                action.accept(e.key, e.value);
        }
        if (modCount != mc)
            throw new ConcurrentModificationException();
    }
}

那么modCount又是什么呢,结合网上搜索出来的以及源码注释的描述,这个参数是用来在HashMap迭代时,可以快速发现错误并结束迭代的。

/**
 * The number of times this HashMap has been structurally modified
 * Structural modifications are those that change the number of mappings in
 * the HashMap or otherwise modify its internal structure (e.g.,
 * rehash).  This field is used to make iterators on Collection-views of
 * the HashMap fail-fast.  (See ConcurrentModificationException).
 */
transient int modCount;

知道这个参数的含义后,点击modCount,查看有哪些地方会修改他的值。发现有这些地方会修改modCount。最后赋值为0的方法(reinitialize)是重新初始化HashMap的参数,这个可以略过。

 

putVal

661行,也是put()实际调用的方法。从源码中我们可以看到,当key存在时,会直接return oldValue结束方法。也就是说只有在插入新的key时会导致modCount增加。

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)
        n = (tab = resize()).length;
    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.equ
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

一曲笛骁奏给谁听

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值