问题
同花顺的笔试题,印象比较深,运行如下代码:
public class Test1_1 {
public static void main(String[] args) {
List<String> list = new ArrayList<string>();
list.add("1");
list.add("2");
for (String str:list){
if ("1".equals(str)){
list.remove(str);
}
}
}
}
public class Test1_1 {
public static void main(String[] args) {
List<String><string> list = new ArrayList<string>();
list.add("1");
list.add("2");
for (String str:list){
if ("2".equals(str)){
list.remove(str);
}
}
}
}
回答两段代码的运行情况,并回答为什么会出现这样的情况。
结果:


不了解机制的情况下,答题时我猜测for( : )的实现还是用指针遍历所以报Nullpointer,所以代码段1的判断误打误撞是正确的,但事实上代码段2的错误并不是因为空指针,而是报ConcurrentModificationException。
ConcurrentModificationException
那么什么是 ConcurrentModificationException 呢?
一般在Vector、ArrayList进行迭代时如果同时对其进行修改就会抛出ConcurrentModificationException异常。
观察ArrayList.java:1009的具体实现如下

源代码
在modCount不等于expectedModCount时会抛出此异常。回过来看Iterator的实现。

/**
* 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;
// prevent creating a synthetic constructor
Itr() {}
public boolean hasNext() {
return cursor != size;
}
@SuppressWarnings("unchecked")
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];
}
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();
}
}
@Override
public void forEachRemaining(Consumer<? super E> action) {
Objects.requireNonNull(action);
final int size = ArrayList.this.size;
int i = cursor;
if (i < size) {
final Object[] es = elementData;
if (i >= es.length)
throw new ConcurrentModificationException();
for (; i < size && modCount == expectedModCount; i++)
action.accept(elementAt(es, i));
// update once at end to reduce heap write traffic
cursor = i;
lastRet = i - 1;
checkForComodification();
}
}
final void checkForComodification() {
if (modCount != expectedModCount)
throw new ConcurrentModificationException();
}
}
好的,先来梳理一下成员变量,顺便抽象一下各个函数的作用。
结构
Itr实现Iterator<E>拥有以下成员变量:
- int cursor; //要返回的下一个元素的索引
- int lastRet = -1; //返回的最后一个元素的索引;如果没有则为-1
- int expectedModCount = modCount; //默认相等
拥有以下函数:
- public boolean hasNext(); //返回 cursor != size (标记小于size就报true)
- public E next(); //调用一次checkForComodification(); 将cursor值赋给i; 判断i是否大于边界size; 判断i是否大于elementData.length()【这块可以不看】; cursor+1,lastSet+1;
- public void remove(); //判断lastSet是否小于0,调用一次checkForComodification(); 调用ArrayList的remove()移除元素; 然后把cursor修改为删除的lastRet的值(相当于i–操作); 最关键的一步,同步expectedModCount和modCount的值。
- checkForComodification(); //判断modCount和expectedModCount是否相等。
出错原因
回看出错原因,是调用next()中 checkModComodification()抛出异常,也就是说modCount不等于expectedModCount,我们没有使用itr()的remove()函数,而是直接使用了ArrayList实例的remove()函数,所以继续回去看ArrayList的remove()描述:


调用了fastRemove()函数,继续进入查看。

好的,fastRemove()函数的描述为:跳过边界检查且不返回已删除值的私有删除方法。
可以看到 modCount++; 因此在foreach中直接调用ArrayList的remove()就会导致modCount和expectedModCount值不同,因而被checkModComodification抓取抛出异常。
更多的思考
了解了报错的原因之后,我发现这并不能解释为什么代码块1就没有报错,并且多次调整代码之后发现,只要是remove() ArrayList中的倒数第二个对象,就不会报错,其余都会报错。如下:

(坑留着以后再填)