package com.test;
import java.util.ArrayList;
import java.util.Iterator;
public class TestList {
public static void main(String[] args) {
ArrayList<String> list = new ArrayList<>();
list.add("One");
list.add("Two");
list.add("Three");
list.add("Four");
Iterator<String> it = list.iterator();
while (it.hasNext()) {
String str = it.next();
System.out.print(str + " ");
if (str.equals("Three")) {
list.remove("Three");
}
}
System.out.println();
System.out.println("List are :" + list);
}
}
输出: 一二三 列表是:[一,二,四]
为什么不抛出ConcurrentModificationException?
但是,以下情况会引发ConcurrentModificationException:
if (str.equals("One")) {
list.remove("One");
}
if (str.equals("Two")) {
list.remove("Two");
}
if (str.equals("Four")) {
list.remove("Four");
}