ConcurrentModificationException是基于java集合中的 快速失败(fail-fast) 机制产生的,在使用迭代器遍历一个集合对象时,如果遍历过程中对集合对象的内容进行了增删改,就会抛出该异常。
快速失败机制使得java的集合类不能在多线程下并发修改,也不能在迭代过程中被修改。
抛异常实例
使用迭代器遍历list,同时使用list.remove方法删除元素,会抛ConcurrentModificationException异常:
public void tryRemove(List<String> strings) {
Iterator<String> it = strings.iterator();
while(it.hasNext()) {
String str = it.next();
if(str.equals("remove") {
strings.remove(str);
}
}
}
抛异常的原因
抛异常是在next方法中,该方法共有两处抛异常,上面的实例中,是在next方法的第一处抛的异常。
public E next() {
if (modCount