这段代码有看上去没问题,但是i运行起来却报错“
private static void demoError(){
List<String> myArrayList = new ArrayList<>();
myArrayList.add("a");
myArrayList.add("b");
myArrayList.add("c");
for (String str : myArrayList) {
if (str.startsWith("a")){
myArrayList.remove(str);
}
}
System.out.println(myArrayList);
}
Exception in thread "main" java.util.ConcurrentModificationException
at java.util.ArrayList$Itr.checkForComodification(ArrayList.java:911)
at java.util.ArrayList$Itr.next(ArrayList.java:861)
at com.ak.sc.audit.center.interfaces.business.audituser.service.TestAuditUserService2.demoError(TestAuditUserService2.java:74)
at com.ak.sc.audit.center.interfaces.business.audituser.service.TestAuditUserService2.main(TestAuditUserService2.java:62)
Disconnected from the target VM, address: '127.0.0.1:60194', transport: 'socket'
这个解释的比较详细:https://juejin.cn/post/6844903569095671816
给出2个解决方案:
第一:删除元素不便利
ArrayList<String> strings = new ArrayList<String>();
strings.add("a");
strings.add("b");
strings.add("c");
strings.add("d");
strings.add("e");
ArrayList<String> tempStrings = new ArrayList<String>();
for (String string : strings) {
if("e".equals(string)){
tempStrings.add(string);
}
}
strings.removeAll(tempStrings);
二:用迭代器
ArrayList<String> strings = new ArrayList<String>();
strings.add("a");
strings.add("b");
strings.add("c");
strings.add("d");
strings.add("e");
Iterator<String> iterator = strings.iterator();
while (iterator.hasNext()){
String element = iterator.next();
if("e".equals(element)){
iterator.remove();
}
}
三、倒序forui删除