gpt4 book ai didi

java - ConcurrentModificationException 从迭代器中删除元素

转载 作者:行者123 更新时间:2023-12-02 01:42:06 25 4
gpt4 key购买 nike

从 map 中删除条目时返回了 ConcurrentModificationException,但我看不出出了什么问题。

    Iterator<String> mapIterator = this.attributeMap.keySet().iterator();
while (mapIterator.hasNext())
{
String attributeName = mapIterator.next();
if (attributeName.matches(pattern))
{
mapIterator.remove();
}
}

最佳答案

在这种情况下,该行 映射迭代器.next()抛出 ConcurrentModificationException 。

这背后的原因是:
有一个 int 变量 modCount,它提供列表大小更改的次数,该值在每次 next() 调用中使用检查函数 checkForCommodification() 中的任何修改。
如果 mapIterator.next() 在迭代对象时发现 modCount 发生变化,那么它将抛出 ConcurrentModificationException

为避免这种情况,请遵循以下几点:

  1. 您可以将列表转换为数组,然后迭代该数组。这种方法适用于中小型列表,但如果列表很大,则会对性能产生很大影响。

  2. 您可以通过将列表放入同步块(synchronized block)中来在迭代时锁定列表。不推荐这种方法,因为它会停止多线程的好处。

  3. 如果您使用的是 JDK1.5 或更高版本,则可以使用 ConcurrentHashMap 和 CopyOnWriteArrayList 类。这是推荐的方法。

关于java - ConcurrentModificationException 从迭代器中删除元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54323391/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com