我無法理解的原因,爲什麼下面的代碼拋出CME,即使它被運行爲單線程應用的java + ConcurrentModificationException的的forEach(增強)循環單線程
import java.util.ArrayList;
import java.util.List;
public class ConcurrentModification {
public static void main(String[] args) {
ConcurrentModification con = new ConcurrentModification();
con.call();
}
void call() {
List<Integer> l = new ArrayList<Integer>();
for (int i = 0; i <= 10000; i++) {
l.add(i);
}
for (Integer j : l) {
if (j % 3 == 0) {
l.remove(j);
}
}
}
}
原因:(在經過答案和其他鏈接後)
You are not permitted to mutate a list while you are iterating over it.
Only Iterator remove's method can be used to delete element from list
For Each loop is using iterator beneath it
but l.remove(j) is not using that iterator, which causes the exception
你從列表中,當你迭代它刪除的項,但不會使用'Iterator.remove'執行刪除操作。有很多重複的 - 我會嘗試找到一個... –