【发布时间】:2025-12-07 12:55:01
【问题描述】:
我有一个简单的HashMap 算法:
HashMap<Integer, Integer> map = new HashMap<>();
map.put(1, 1);
map.put(2, 2);
map.put(3, 3);
Iterator<Integer> it = map.keySet().iterator();
while(it.hasNext()) {
Integer key = it.next();
if (key.equals(2)) {
map.put(1, 2);
}
}
这工作正常。 但是当我将条件体修改为:
if (key.equals(2)) {
map.put(0, 2); // changed index '1' to '0'
}
它总是抛出java.util.ConcurrentModificationException。小于0 的键值也是如此。
我错过了什么?
编辑
似乎如果我将删除第三个Map 元素:
map.put(1, 1);
map.put(2, 2);
// map.put(3, 3);
一切正常
【问题讨论】:
-
ConcurrentModificationException在您修改当前正在迭代的集合时发生。迭代器不会被通知基础集合的更改。创建要迭代的集合的副本,以避免这种情况。第一个工作正常,因为您不更改集合的大小。 -
但
map.put(1, 2);工作正常 - 我会理解是否每次都会抛出异常但为什么它只发生在<=0键上? -
put(100000,x) 也会这样做
-
在这个特定的 hasmap 迭代器实现中,重要的是集合的大小,而不是实际的键值对
标签: java collections