问题出现
这次写代码写的比较急出现的一个问题,在遍历的时候使用Iterator在删除的时候用了List的remove,就出现了java.util.ConcurrentModificationException;
public static void main(String[] args) {
List<Integer> li=new ArrayList<Integer>(){{add(1);add(1);add(1);add(1);add(1);add(1);add(1);}};
Iterator<Integer> iterator = li.iterator();
while (iterator.hasNext()){
Integer next = iterator.next();
li.remove(next);
}
}
原因
看到报错,找到报错原因
final void checkForComodification() {
if (modCount != expectedModCount)
throw new ConcurrentModificationException();
}
是因为modCount和expectedModCount不相等,那modCount和expectedModCount是什么呢?
全局找modCount修改地方,发现增删等地方会修改这个计数变量。
public boolean add(E e) {
ensureCapacityInternal(size + 1); // Increments modCount!!
elementData[size++] = e;
return true;
}
private void ensureCapacityInternal(int minCapacity) {
if (elementData == DEFAULTCAPACITY_EMPTY_ELEMENTDATA) {
minCapacity = Math.max(DEFAULT_CAPACITY, minCapacity);
}
ensureExplicitCapacity(minCapacity);
}
private void ensureExplicitCapacity(int minCapacity) {
modCount++;
// overflow-conscious code
if (minCapacity - elementData.length > 0)
grow(minCapacity);
}
public E remove(int index) {
rangeCheck(index);
modCount++;
E oldValue = elementData(index);
int numMoved = size - index - 1;
if (numMoved > 0)
System.arraycopy(elementData, index+1, elementData, index,
numMoved);
elementData[--size] = null; // clear to let GC do its work
return oldValue;
}
发现会+这个值,就是修改次数。
那看下expectedModCount又是什么,发现
/**
* An optimized version of AbstractList.Itr
*/
private class Itr implements Iterator<E> {
int cursor; // index of next element to return
int lastRet = -1; // index of last element returned; -1 if no such
int expectedModCount = modCount;
...
}
发现在初始化迭代器时expectedModCount等于modCount,但是remove会++那就导致了不相等,为啥不在remove的时候expectedModCount–呢,为啥这样设计呢?大概是设计者不想在迭代的时候,集合去操作,而是交给迭代器,如下:
public void remove() {
if (lastRet < 0)
throw new IllegalStateException();
checkForComodification();
try {
ArrayList.this.remove(lastRet);
cursor = lastRet;
lastRet = -1;
expectedModCount = modCount;
} catch (IndexOutOfBoundsException ex) {
throw new ConcurrentModificationException();
}
}
所以删除的时候使用迭代器的方法就行。