62,621
社区成员
发帖
与我相关
我的任务
分享
//AbstractCollection
public boolean removeAll(Collection<?> c) {
boolean modified = false;
Iterator<?> e = iterator();
while (e.hasNext()) {
if (c.contains(e.next())) {
e.remove();
modified = true;
}
}
return modified;
}
//AbstractCollection
public boolean removeAll(Collection<?> c) {
boolean modified = false;
Iterator<?> e = iterator();
while (e.hasNext()) {
if (c.contains(e.next())) {
e.remove();
modified = true;
}
}
return modified;
}
//AbstractList
public Iterator<E> iterator() {
return new Itr();
}
//remove方法,需要在AbstractList的子类中实现
public E remove(int index) {
throw new UnsupportedOperationException();
}
private class Itr implements Iterator<E> {
....
/*这个字段的意思,根据sun的英文注释,我的理解是,记录了列表的结构性改变次数,如果迭代器希望防止对列表结构的并发性修改,就得在每次改变列表结构的列表操作中,使该字段仅仅增加1;
这里Iterator的实现,将结构变化次数赋给expectedModCount保存,*/
int expectedModCount = modCount;
public void remove() {
if (lastRet == -1)
throw new IllegalStateException();
checkForComodification();
try {
//这里实际采用AbstractList的子类中的remove方法来删除元素
AbstractList.this.remove(lastRet);
if (lastRet < cursor)
cursor--;
lastRet = -1;
/*如果子类中想提供一个快速失败的迭代器,必须在能改变列表结构的方法中仅使modCount增加1,这样,经过上边的AbstractList.this.remove(lastRet)操作(实际上是ArrayList的remove方法,ArrayList提供快速失败的迭代器),modCount增加了,需要重新赋给expectedModCount保存起来,因为这次结构修改是迭代器自己做的,不属于并发的修改。*/
expectedModCount = modCount;
} catch (IndexOutOfBoundsException e) {
throw new ConcurrentModificationException();
}
}
/*检测结构变化次数在迭代操作中是否有变,如果有变,则说明在迭代过程中存在并发性的列表结构修改,抛出ConcurrentModificationException*/
final void checkForComodification() {
if (modCount != expectedModCount)
throw new ConcurrentModificationException();
}
....
}
//ArrayList中的remove方法,覆盖了AbstractList中的remove方法
public E remove(int index) {
RangeCheck(index);
modCount++;//增加结构化修改次数
E oldValue = (E) elementData[index];
/*获得被删元素后面的一个元素的下标,从这个元素开始一直到最后,应该向前移一位*/
int numMoved = size - index - 1;
if (numMoved > 0)
//将元素前移
System.arraycopy(elementData, index+1, elementData, index,
numMoved);
//将最后一个元素置为null,失去引用的对象由gc收集
elementData[--size] = null; // Let gc do its work
return oldValue;
}