并发修改异常 java.util.ConcurrentModificationException
问题:
代码:
//使用该List集合会出现 java.util.ConcurrentModificationException
//List<Map<String,Object>> stuList = new ArrayList<>();
CopyOnWriteArrayList<Map<String,Object>> stuList = new CopyOnWriteArrayList<>();
{
Map<String,Object> map1 = new HashMap<>();
Map<String,Object> map2 = new HashMap<>();
Map<String,Object> map3 = new HashMap<>();
stuList.add(map1);
stuList.add(map2);
stuList.add(map3);
map1.put("name","小刘");
map2.put("name","小王");
map3.put("name","小李");
}
@Test
public void test(){
stuList.forEach(item ->{
String name = item.get("name").toString();
System.out.println(name);
if("小王".equals(name)){
Map<String,Object> map4 = new HashMap<>();
stuList.add(map4);
map4.put("name","小郎");
}
});
System.out.println(stuList);
}
@Test
public void test1(){
ConcurrentMap<String,Object> map = new ConcurrentHashMap<>();
//使用该Map集合会出现 java.util.ConcurrentModificationException
//Map<String,Object> map = new HashMap<>();
map.put("name","A");
map.put("age","B");
map.put("status","C");
for (Map.Entry<String, Object> entry : map.entrySet()) {
String key = entry.getKey();
String value = (String)entry.getValue();
System.out.println("key:" + key + ",value:" + value);
if("B".equals(value)){
map.put("other","D");
}
}
System.out.println(map);
}