Collections 迭代器如何从集合中同时读取和删除元素?
我创建了以下代码。 我的目标是检查在读取集合时是否使用迭代器删除元素。 有人能解释一下为什么在将hashmap的值集合添加到链接列表中并为该列表创建迭代器后会抛出concurrentModificationException,但在将集合添加到列表中获得迭代器时不会抛出concurrentModificationException 我知道原因很简单,我想买些容易买到的东西,但我只想确认一下我的想法是否正确 还有另外两点。 1.因为hashmap不是线程安全的,所以为什么我们不能在迭代器读取时向它添加任何元素? 2.如果是,那么我们如何从地图中删除元素Collections 迭代器如何从集合中同时读取和删除元素?,collections,linked-list,hashmap,thread-safety,concurrenthashmap,Collections,Linked List,Hashmap,Thread Safety,Concurrenthashmap,我创建了以下代码。 我的目标是检查在读取集合时是否使用迭代器删除元素。 有人能解释一下为什么在将hashmap的值集合添加到链接列表中并为该列表创建迭代器后会抛出concurrentModificationException,但在将集合添加到列表中获得迭代器时不会抛出concurrentModificationException 我知道原因很简单,我想买些容易买到的东西,但我只想确认一下我的想法是否正确 还有另外两点。 1.因为hashmap不是线程安全的,所以为什么我们不能在迭代器读取时向它添
package com.Users;
import java.util.HashMap;
import java.util.Iterator;
import java.util.LinkedList;
public class Temp{
public static void main(String arg[]){
HashMap<String, String> map=new HashMap();
map.put("A", "B");
map.put("C", "D");
LinkedList<String> list=new LinkedList<>();
//****** concurent exception is thrown when ever line 1 is swapped with line 2 ******
Iterator<String> iterator=list.iterator(); //line no. 1
list.addAll(map.values()); //line no. 2
//******************
while(iterator.hasNext()){
if(iterator.next().equals("B")){
iterator.remove();
}
}
System.out.println(list);
}
}
package.com.Users;
导入java.util.HashMap;
导入java.util.Iterator;
导入java.util.LinkedList;
公共类临时工{
公共静态void main(字符串arg[]){
HashMap=newHashMap();
地图放置(“A”、“B”);
地图放置(“C”、“D”);
LinkedList=新建LinkedList();
//******当第1行与第2行交换时,将引发concurent异常******
迭代器迭代器=list.Iterator();//第1行
list.addAll(map.values());//第2行
//******************
while(iterator.hasNext()){
if(iterator.next().equals(“B”)){
iterator.remove();
}
}
系统输出打印项次(列表);
}
}
HashMap上的迭代器本质上是故障快速的
,这意味着它们会尽快中止操作,并立即暴露故障
集合维护一个名为modCount
的内部计数器。无论何时从集合中添加或删除项,都会修改此计数器
迭代时,每次调用next()时,都会将modCount的当前值与初始值进行比较。如果存在不匹配,它将抛出ConcurrentModificationException
,从而中止整个操作
iterator.remove()
中使用了迭代器的remove()
方法。
如果我们使用集合的remove()
方法,那么也会抛出ConcurrentModificationException
阅读详细解释。有道理!!谢谢你的解释。