當我運行下面的一段代碼時,我的程序出現ConcurrentModificationException
。通過一些研究,我發現列表中的元素在迭代器循環中無法添加或刪除。我現在要做什麼來移除List<Bean>
中的元素?爲什麼從列表中刪除元素會引發ConcurrentModificationException?
for (Iterator<Entry<String, List<Bean>>> iterator = dataMap.entrySet().iterator(); iterator.hasNext();) {
Entry<String, List<Bean>> entry = (Entry<String, List<Bean>>)iterator.next();
List<Bean> dateWiseValues = (List<Bean>) entry.getValue();
int j = 0;
for (Bean statBean : dateWiseValues) {
for (int i = 0; i < commonElements.size(); i++) {
if(statBean.getDate().equalsIgnoreCase(commonElements.get(i))) {
//remove the bean
entry.getValue().remove(j);
}
}
j++;
}
}
後刪除它,或者你可以將您的值複製到一個「鏡像」列表和循環鏡子,而從實際列表 – 2013-04-19 23:55:44
這消除他們也可能會感興趣:http://docs.oracle.com/javase /1.5.0/docs/api/java/util/concurrent/CopyOnWriteArrayList.html – subarachnid 2013-04-20 00:00:33
@Saraarachnid,那好多了,把它當作答案 – 2013-04-20 00:01:55