在对其List<Map<String, Object>>集合进行移除的时候,报错:java.util.ConcurrentModificationException;
List<Map<String, Object>> scheduleMaps = new ArrayList<Map<String, Object>>();
for(Map<String, Object> m : scheduleMaps) {
for(String k : m.keySet()) { String kString = m.get(k).toString(); if(!(kString.contains("XXX")) && ("colums".equals(k.trim()) || "columsOther".equals(k.trim()))) { m.remove(k); } }}
原因和解决方法:
使用“ConcurrentHashMap”替换HashMap,ConcurrentHashMap会自己检查修改操作,对其加锁,也可针对插入操作。 import java.util.concurrent.*;
把
Map<String, Object> scheduleMap = new HashMap<String, Object>();
改成如下:
Map<String, Object> scheduleMap = new ConcurrentHashMap<String, Object>();
补充:
在使用iterator.hasNext()操作迭代器的时候,如果此时迭代的对象发生改变,比如插入了新数据,或者有数据被删除。
mport java.util.*; public class Main { public static void main(String args[]) { Main main = new Main(); main.test(); } public void test() { Map bb = new HashMap(); bb.put("1", "wj"); bb.put("2", "ry"); Iterator it = bb.keySet().iterator(); while(it.hasNext()) { Object ele = it.next(); bb.remove(ele); //wrong } System.out.println("Success!"); } }
原因:Iterator做遍历的时候,HashMap被修改(bb.remove(ele), size-1),Iterator(Object ele=it.next())会检查HashMap的size,size发生变化,抛出错误ConcurrentModificationException。
解决办法:
1) 通过Iterator修改Hashtable while(it.hasNext()) { Object ele = it.next(); it.remove(); }
2) 根据实际程序,您自己手动给Iterator遍历的那段程序加锁,给修改HashMap的那段程序加锁。
3) 使用“ConcurrentHashMap”替换HashMap,ConcurrentHashMap会自己检查修改操作,对其加锁,也可针对插入操作。 import java.util.concurrent.*;