/**
* The number of times this list has been <i>structurally modified</i>.
* Structural modifications are those that change the size of the
* list, or otherwise perturb it in such a fashion that iterations in
* progress may yield incorrect results.
*
* <p>This field is used by the iterator and list iterator implementation
* returned by the {@code iterator} and {@code listIterator} methods.
* If the value of this field changes unexpectedly, the iterator (or list
* iterator) will throw a {@code ConcurrentModificationException} in
* response to the {@code next}, {@code remove}, {@code previous},
* {@code set} or {@code add} operations. This provides
* <i>fail-fast</i> behavior, rather than non-deterministic behavior in
* the face of concurrent modification during iteration.
*
* <p><b>Use of this field by subclasses is optional.</b> If a subclass
* wishes to provide fail-fast iterators (and list iterators), then it
* merely has to increment this field in its {@code add(int, E)} and
* {@code remove(int)} methods (and any other methods that it overrides
* that result in structural modifications to the list). A single call to
* {@code add(int, E)} or {@code remove(int)} must add no more than
* one to this field, or the iterators (and list iterators) will throw
* bogus {@code ConcurrentModificationExceptions}. If an implementation
* does not wish to provide fail-fast iterators, this field may be
* ignored.
*/
protected transient int modCount = 0;
在父類AbstractList中定義了一個int型的屬性:modCount,記錄了ArrayList結構性變化的次數。
protected transient int modCount = 0;
在ArrayList的所有涉及結構變化的方法中都增加modCount的值,包括:add()、remove()、addAll()、removeRange()及clear()方法。這些方法每調用一次,modCount的值就加1。
注:add()及addAll()方法的modCount的值是在其中調用的ensureCapacity()方法中增加的。
AbstractList中的iterator()方法(ArrayList直接繼承了這個方法)使用了一個私有內部成員類Itr,生成一個Itr對象(Iterator接口)返回:
public Iterator iterator() { return new Itr(); }
Itr實現了Iterator()接口,其中也定義了一個int型的屬性:expectedModCount,這個屬性在Itr類初始化時被賦予ArrayList對象的modCount屬性的值。
int expectedModCount = modCount;
注:內部成員類Itr也是ArrayList類的一個成員,它可以訪問所有的AbstractList的屬性和方法。理解了這一點,Itr類的實現就容易理解了。
在Itr.hasNext()方法中:
public boolean hasNext() { return cursor != size(); }
調用了AbstractList的size()方法,比較當前光標位置是否越界。
在Itr.next()方法中,Itr也調用了定義在AbstractList中的get(int)方法,返回當前光標處的元素:
public Object next()
{
try
{
Object next = get(cursor);
checkForComodification();
lastRet = cursor++;
return next;
}
catch(IndexOutOfBoundsException e)
{
checkForComodification();
throw new NoSuchElementException();
}
}
注意,在next()方法中調用了checkForComodification()方法,進行對修改的同步檢查:
final void checkForComodification()
{
if (modCount != expectedModCount) throw new ConcurrentModificationException(); }
現在對modCount和expectedModCount的作用應該非常清楚了。在對一個集合對象進行跌代操作的同時,並不限制對集合對象的元素進行操 作,這些操作包括一些可能引起跌代錯誤的add()或remove()等危險操作。在AbstractList中,使用了一個簡單的機制來規避這些風險。 這就是modCount和expectedModCount的作用所在。