问题描述:使用增强for循环遍历集合,如果遍历过程中去除第一个或者最后一个元素会报错,去除中间的元素不会报错:Exception in thread “main” java.util.ConcurrentModificationException
不知道这个是怎么回事,好像和指针有关吧(暂时不了解),为了避免此类问题的出现,可以使用迭代器或者
普通for循环来解决。
1.使用迭代器
代码举例:
public static void removeElement(List<Integer> list) {
Iterator<Integer> it = list.iterator();
while(it.hasNext()) {
Integer id = it.next();
if (id == 2) {
it.remove();
}
}
}
2.使用普通for循环,如果删除需要i–
public static void removeElement(List list) {
int len = list.size();
for(int i = 0; i < len; i++) {
if(list.get(i) == 2) {
list.remove(i);
i--;
}
}
}
本文探讨了在Java中使用增强for循环遍历集合时删除元素导致的并发修改异常问题,并提供了两种解决方案:使用迭代器和普通for循环。通过代码示例展示了如何正确地在遍历过程中移除集合中的特定元素。
993

被折叠的 条评论
为什么被折叠?



