[英]Is it safe to delete HashMap's entry when iterating over its values?
Assuming I know the key, is it possible to remove it when iterating over 假设我知道密钥,可以在迭代时将其删除
for (ExampleClass e : map.values()) {
if (condition) {
map.remove(key);
}
}
I have found a related question ( iterating over and removing from a map ), but it assumes we are iterating over the key set. 我发现了一个相关的问题( 遍历和从地图中删除 ),但是它假定我们正在遍历键集。 Does the same apply to the value set?
设定值是否相同?
From the HashMap
javadoc : 从
HashMap
javadoc中 :
The iterators returned by all of this class's "collection view methods" are fail-fast: if the map is structurally modified at any time after the iterator is created, in any way except through the iterator's own remove method, the iterator will throw a
ConcurrentModificationException
.由此类的所有“集合视图方法”返回的迭代器都是快速失败的:如果在创建迭代器后的任何时候以任何方式对映射进行结构修改,则除了通过迭代器自己的remove方法之外,迭代器都会抛出
ConcurrentModificationException
。
So you can't use map.remove(key)
. 因此,您不能使用
map.remove(key)
。
From the javadoc for HashMap#values()
: 从javadoc中获取
HashMap#values()
:
The collection supports element removal, which removes the corresponding mapping from the map, via the Iterator.remove, Collection.remove, removeAll, retainAll and clear operations.
集合支持元素删除,该元素通过Iterator.remove,Collection.remove,removeAll,retainAll和clear操作从映射中删除相应的映射。
So you can use Iterator#remove()
to remove entries from the value set. 因此,您可以使用
Iterator#remove()
从值集中删除条目。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.