AbstractList类提供了一个受保护的方法modCount,这个方法将在每次对列表进行结构修改时自增,用于实现检测并发修改的机制。AbstractList类还提供了两个抽象方法 listIterator()和 size(),这两个方法的实现由具体的子类来完成。
为了实现Iterator
以下是简化版的AbstractList和Itr代码示例:
public abstract class AbstractList extends AbstractCollection implements List {
protected int modCount;
public Iterator iterator() {
return new Itr();
}
public abstract ListIterator listIterator(int index);
public abstract int size();
private class Itr implements Iterator {
int cursor;
int expectedModCount = modCount;
public boolean hasNext() {
return cursor != size();
}
public E next() {
checkForComodification();
int i = cursor;
cursor = i + 1;
return AbstractList.this.get(i);
}
public void remove() {
// 省略实现
}
final void checkForComodification() {
if (modCount != expectedModCount)
throw new ConcurrentModificationException();
}
}
}
public class ArrayList extends AbstractList implements List, RandomAccess, Cloneable, Serializable {
private transient Object[] elementData;
public int size() {
return size;
}
public ListIterator listIterator(int index) {
// 省略实现
}
}