遍历删除list中元素注意问题。
foreach遍历list时候,其实就是根据list对象创建一个Iterator迭代对象,用这个迭代对象来遍历list,相当于list对象中元素的遍历托管给了Iterator,你如果要对list进行增删操作,都必须经过Iterator,否则Iterator遍历时会乱。其实,每次foreach迭代的时候都有两部操作:
- iterator.hasNext() //判断是否有下个元素
- item = iterator.next() //下个元素是什么,并赋值给上面例子中的item变量
hasNext()方法的代码如下:
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];
}
final void checkForComodification() {
if (modCount != expectedModCount)
throw new ConcurrentModificationException();
}
对list的任何结构性操作modCount都会自增,而遍历list的整个过程中不允许list结构变化。