从源码入手,深入理解Collections集合中的并发修改异常(checkForComodification)
我们再遍历Collections集合的时候,会常常用到的就是迭代器,但是这种方式只能遍历,假如我们想获得一个元素后,再添加一个元素,这时候就会抛出并发修改异常,如果这时候引用的类型是Collections,我们就没有其它的的方法来遍历集合。因为该接口没有提供带索引的方式获取元素。就需要用到它的子接口List或者实现类ArrayList.而为什么Coolections接口之类用迭代器来遍历了?(当然你也可以向下转型),就是在该接口中原本就定义了产生一个迭代器的方法
而子类ArrayList实现了该方法:
说明:
public interface List<E> { Iterator<E> iterator(); boolean add(E e); } public abstract class AbstractList<E> { protected int modCount = 0;//实际修改集合的次数 } public class ArrayList<E> extends AbstractList<E> implements List<E> { public E get(int index) { Objects.checkIndex(index, size); return elementData(index); } public boolean add(E e) { modCount++;//修改集合的次数加一 add(e, elementData, size); return true; } public Iterator<E> iterator() { return new Itr();//返回迭代器对象 } //实例内部类 private class Itr implements Iterator<E> { int expectedModCount = modCount; /* modCount:实际修改集合的次数 expectedModCount:预期修改集合的次数 */ public E next() { checkForComodification();//检查实际修改的集合次数和预期的修改次数是否相等 int i = cursor; if (i >= size) throw new NoSuchElementException(); Object[] elementData = ArrayList.this.elementData;//实例内部类中调用外部类的元素 if (i >= elementData.length) throw new ConcurrentModificationException(); cursor = i + 1; return (E) elementData[lastRet = i]; } final void checkForComodification() { if (modCount != expectedModCount) throw new ConcurrentModificationException();//实际修改次数与预期修改次数不相等,抛出异常,如果我们不人为处理,就会交给jvm,程序异常终止! } } }
总的来说产生了一个迭代器对象以后,预期修改集合的次数(expectedModCount)初始值与我们当前集合的实际修改集合的次数相等,预期修改集合的次数(expectedModCount)这个值是不会再修改的,如过我们再对集合中的元素进行增删改等相关操作(查操作 modCount没有改变),就会导致 modCount++了,从而导致 modCount和expectedModCount不想等,从而引发并发修改异常,但是我现在还并不能理解为什么这样设计,可能是为了安全考虑。为了解决这样的问题,我们就需要用索引的方式去遍历改集合,但是Collections中并没有定义含索引的操作,所以我们需要向下转型为List或者ArryList等来进行操作!