【发布时间】:2012-01-01 15:11:24
【问题描述】:
注意:我知道Iterator#remove() 方法。
在下面的代码示例中,我不明白为什么main 方法中的List.remove 抛出ConcurrentModificationException,但remove 方法中不是。
public class RemoveListElementDemo {
private static final List<Integer> integerList;
static {
integerList = new ArrayList<Integer>();
integerList.add(1);
integerList.add(2);
integerList.add(3);
}
public static void remove(Integer toRemove) {
for(Integer integer : integerList) {
if(integer.equals(toRemove)) {
integerList.remove(integer);
}
}
}
public static void main(String... args) {
remove(Integer.valueOf(2));
Integer toRemove = Integer.valueOf(3);
for(Integer integer : integerList) {
if(integer.equals(toRemove)) {
integerList.remove(integer);
}
}
}
}
【问题讨论】:
-
在迭代列表时从列表中删除元素的唯一安全方法是使用
Iterator#remove()。你为什么要这样做? -
@MattBall:我只是想看看这里可能是什么原因。因为,这两种方法中的“增强型 for 循环”是相同的,但一种抛出
ConcurrentModificationException而另一种则没有。 -
您删除的元素有所不同。在该方法中,您删除了“中间元素”。主要是删除最后一个。如果您交换数字,您的方法中会出现异常。仍然不确定为什么会这样。
-
我遇到了类似的问题,当我的循环迭代了一个在我删除循环中的项目后不存在的位置时。我只是通过在循环中添加
return;来解决这个问题。 -
在 java8 Android 上,删除除最后一个以外的元素会调用 ConcurrentModificationException。所以对于你的情况,删除函数会得到一个与你之前观察到的相反的异常。
标签: java list concurrentmodification foreach