public class TestIterator{
public static void main(String[] args) {
List<String> aList = new ArrayList<String>();
aList.add("aaa");
aList.add("bbb");
aList.add("asdf");
aList.add("jvaa");
aList.add("aaaa");
aList.add("itcast");
System.out.println(aList);
delElements1(aList);
delElements2(aList);
delElements3(aList);
System.out.println(aList);
}
public static void delElements1(List<String> aList) {
for (String str : aList) {
if (str.equals("aaa")) {
aList.remove(str);
}
}
}
public static void delElements2(List<String> aList){
Iterator<String> it = aList.iterator();
while(it.hasNext()){
String str = it.next();
if(str.equals("aaa")){
aList.remove(str);
}
}
}
public static void delElements3(List<String> aList){
Iterator<String> it = aList.iterator();
while(it.hasNext()){
String str = it.next();
if(str.equals("aaa")){
it.remove();
}
}
}
}
以上代码中delElements1,delElements2都会报异常:Exception in thread "main" java.util.ConcurrentModificationException,而delElements3则不会报异常,请问这是为什么呢? |