正在用Iterator迭代器循环操作的集合不能调用集合的删除方法,否则就会报异常:ConcurrentModificationException。 (调用迭代器的remove方法可以)
package test;
import java.io.*;
import java.util.*;
public class Demo {
public static void main(String[] args) throws IOException, ClassNotFoundException {
ArrayList<String> list=new ArrayList<>();
list.add("one");
list.add("two");
list.add("three");
list.add("four");
list.add("five");
Iterator<String> iterator = list.iterator();
while (iterator.hasNext()){
String str=iterator.next();
if(str.contains("t")){
list.remove(str);
}
}
System.out.println(list);
}
}