集合遍歷過程中若結構被修改(增/刪元素),立即拋出 ConcurrentModificationException,而非產生不確定行為。屬於「盡力而為」的保護機制,不保證 100% 捕獲。
add/remove/clearList<String> list = new ArrayList<>(Arrays.asList("a1","a2","a3"));
for (String s : list) {
list.remove(s); // 直接修改集合 → CME
}
Iterator<String> it = list.iterator();
while (it.hasNext()) {
String s = it.next();
if (shouldRemove(s)) it.remove(); // 安全刪除
}
原理:Iterator 內部維護 expectedModCount,調用 it.remove() 會同步更新此計數,與集合 modCount 保持一致。
List<String> list = Arrays.asList("a","b","c");
list.iterator().remove(); // UnsupportedOperationException
原因:Arrays.asList 返回的是 java.util.Arrays.ArrayList(內部類),未實現 remove(),非 java.util.ArrayList。此列表為固定長度視圖。
ArrayList 維護 transient int modCountexpectedModCount = modCountnext() 前檢查 if (modCount != expectedModCount) throw CMEIterator.remove() 內部調用 ArrayList.remove(index) 並同步 expectedModCount = modCountArrays.asList 結果不可結構性修改ConcurrentHashMap、CopyOnWriteArrayList)遍歷時不拋 CME,但可能讀到舊數據