有个ArrayList
ArrayList<Integer> list = new ArrayList<Integer>();
list.add(1);
list.add(3);
list.add(1);
list.add(4);
当在foreach list时删除一个list中的元素就会出现 java.util.ConcurrentModificationException ,像这样:
for (Integer integer : list) {
if (1 == integer) {
list.remove(integer);
}
}
原因是
- ArrayList有个modCount字段表示ArrayList被修改的次数
- foreach调用iterator接口
- 在获取iterator的时候ArrayList的modCount被保存在iterator的expectedModCount中
- 每次修改ArrayList的时候modCount就会改变。
- 在每次调用iterator的hasNext和next方法的时候,会先检查ArrayList的modCount和iterator的expectedModCount是否相同,不同就抛异常。
我的做法
Iterator<Integer> iterator = list.iterator();
while (iterator.hasNext()) {
Integer next = iterator.next();
if (1 == next) {
iterator.remove();
}
}