最新文章

遍历 Collection 时删除元素

遍历 Collection 时删除元素

其实标题我想用《为什么foreach边循环边移除元素要用Iterator?》可是太长。

不用Iterator,用Collection.remove(),会报ConcurrentModificationException错误。

for(Integer i : list) {
  list.remove(i); //Throw ConcurrentModificationException
}

其实使用foreach的时候,会自动生成一个Iterator来遍历list。不只是remove,使用add、clear等方法一样会出错。

拿ArrayList来说,它有一个私有的Iterator接口的内部类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;
  	
  //sevrval methods
}

使用Iterator来遍历ArrayList实际上是通过两个指针来遍历ArrayList底层的数组:cursor是下一个返回的元素在数组中的下标;lastRet是上一个元素的下标。还有一个重要的expectedModCount使用的是ArrayList的modCount的(modCount具体是什么意思下文会提到)。