ConcurrentModificationException
遍歷集合,批量刪除時,遇到ConcurrentModificationException
因為操作的集合會在過程中遇到結構性的改變,例如:
HashMap<String, String> testMap = new HashMap<String, String>();
testMap.put("1", "a");
testMap.put("2", "b");
testMap.put("3", "c");
Set<Map.Entry<String,String>> enterySet = testMap.entrySet();

for(Iterator<Map.Entry<String, String>> i = enterySet.iterator(); i.hasNext();){
Map.Entry<String, String> entry = i.next();
if(entry.getValue().equalsIgnoreCase("a")){
testMap.remove(entry.getKey());
}
}
解決方法:不要在集合上刪除,而是在迭代器上刪除:i.remove();
p.s.還有另外一個可能性是多線程同時操作該集合了,那需要進行同步來避免。
因為操作的集合會在過程中遇到結構性的改變,例如:














解決方法:不要在集合上刪除,而是在迭代器上刪除:i.remove();
p.s.還有另外一個可能性是多線程同時操作該集合了,那需要進行同步來避免。
posted on 2010-06-11 13:57 cerulean 閱讀(379) 評論(0) 編輯 收藏 所屬分類: Java