普通的增强for循环遍历时移出元素报错
package com.fridge.controller.cms;
import java.util.ArrayList;
import java.util.List;
/**
* @program: mythicalanimals
* @description: 集合遍历时移出元素demo
* @author: TheEternity Zhang
* @create: 2020-06-08 14:27
*/
public class ListIteratorDemo {
public static void main(String[] args) {
List<String> list = new ArrayList<>();
list.add("abc");
list.add("abe");
list.add("hgf");
list.add("zzx");
for (String str: list) {
if(str.contains("a")){
list.remove(str);
}else{
System.out.println(str);
}
}
System.out.println("集合的数量:"+list.size());
}
}
抛出ConcurrentModificationException异常
Connected to the target VM, address: '127.0.0.1:62068', transport: 'socket'
Exception in thread "main" java.util.ConcurrentModificationException
at java.util.ArrayList$Itr.checkForComodification(ArrayList.java:909)
at java.util.ArrayList$Itr.next(ArrayList.java:859)
at com.fridge.controller.cms.ListIteratorDemo.main(ListIteratorDemo.java:19)
Disconnected from the target VM, address: '127.0.0.1:62068', transport: 'socket'
使用Iterator在遍历时移出元素
package com.fridge.controller.cms;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
/**
* @program: mythicalanimals
* @description: 集合遍历时移出元素demo
* @author: TheEternity Zhang
* @create: 2020-06-08 14:27
*/
public class ListIteratorDemo {
public static void main(String[] args) {
List<String> list = new ArrayList<>();
list.add("abc");
list.add("abe");
list.add("hgf");
list.add("zzx");
Iterator<String> iterator = list.iterator();
while (iterator.hasNext()){
String str = iterator.next();
if(str.contains("a")){
iterator.remove();
}else{
System.out.println(str);
}
}
System.out.println("集合的数量:"+list.size());
}
}
结果
hgf
zzx
集合的数量:2