示例代碼:
public class TestList {
public static void main(String[] args) {
List<String> a = new ArrayList<String>();
a.add("1");
a.add("2");
a.add("3");
for (String tmp : a) {
if ("2".equals(tmp)) {
a.remove(tmp);
}
}
System.out.println(a);
}
}
這個示例運行最後運行成功. 但是 爲什麼沒有拋出ConcurrentModificationException異常呢?
查看代碼後發現 , 問題出在這裏,
當我們遍歷到 , 最後一項前一項的時候 , 這個時候size依然是3 . 而ArrayList的Iterator這裏,
public boolean hasNext() {
return cursor != size;
}
這裏判斷是否還有下一項.這裏cursor是1. 很顯然不等於size.
所以進入next
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];
}
next裏, cursor這時候變爲2 . 接下來我們刪除這一項
public boolean remove(Object o) {
if (o == null) {
for (int index = 0; index < size; index++)
if (elementData[index] == null) {
fastRemove(index);
return true;
}
} else {
for (int index = 0; index < size; index++)
if (o.equals(elementData[index])) {
fastRemove(index);
return true;
}
}
return false;
}
這裏進入到fastRemove.
private void fastRemove(int index) {
modCount++;
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
}
modCount確實是++了, 但是我們的size這時候也做了--size操作,導致size變爲2.
那麼下次hasNext的時候判斷cursor!=size , 返回的是false. 於是其實根本沒有遍歷到最後一項, 從而也沒有做checkForComodification的操作, 從而這裏不報錯.