在對一個(gè)對集合進(jìn)行遍歷的時(shí)候,不要對集合進(jìn)行add或者remove等操作。
原因:
ArrayList的remove方法只是修改了modCount的值,并沒有修改expectedModCount,導(dǎo)致modCount和expectedModCount的值的不一致性,當(dāng)next()時(shí)則拋出ConcurrentModificationException異常。因此使用Iterator遍歷集合時(shí),不要改動(dòng)被迭代的對象。
List<MyPost> items = focusQuestions.list;
for (MyPost item : items) {
if (item.isChecked())
items.remove(item);
}
報(bào)錯(cuò):
java.util.ConcurrentModificationException
at java.util.ArrayList$ArrayListIterator.next(ArrayList.java:573)
相關(guān)文章:
java.util.ConcurrentModificationException 出現(xiàn)的原因和解決辦法