在对List、Set、Map执行遍历删除或添加等改变集合个数的操作时,不能使用普通的while、for循环或增强for。会抛出ConcurrentModificationException异常或者没有达到删除的需求。在遍历时删除元素,需要使用迭代器的方式。
ArrayList源码中说明的报异常原因:
* <p>The iterators returned by this class's <tt>iterator</tt> and
* <tt>listIterator</tt> methods are <i>fail-fast</i>: if the list is
* structurally modified at any time after the iterator is created, in any way
* except through the iterator's own <tt>remove</tt> or <tt>add</tt> methods,
* the iterator will throw a {@link ConcurrentModificationException}. Thus, in
* the face of concurrent modification, the iterator fails quickly and cleanly,
* rather than risking arbitrary