问题复现:
List<String> list = new ArrayList<>();
list.add("11");
list.add("55");
list.add("sw");
list.add("33");
list.add("2sw");
System.out.println(list.size()+":"+list);
for (String s:list){
if(s.equals("11")){
list.remove(s);
}
if(s.equals("sw")){
list.remove(s);
}
}
System.out.println(list.size()+":"+list);
以上代码编译正常,但是运行报Exception in thread "main" java.util.ConcurrentModificationException错误!
解决:
List<String> list = new ArrayList<>();
list.add("11");
list.add("55");
list.add("sw");
list.add("33");
list.add("2sw");
System.out.println(list.size() + ":" + list);
Iterator<String> iterator = list.iterator();
while (iterator.hasNext()) {
String string = iterator.next();
if (string.equals("11")) {
iterator.remove();
}
if (string.equals("sw")) {
iterator.remove();
}
}
System.out.println(list.size() + ":" + list);
用迭代模式删除正常!
具体参考:https://www.cnblogs.com/dolphin0520/p/3933551.html