首先看下下面的各種删除list元素的例子
public static void main(String[] args) {
List list = new ArrayList<>(Arrays.asList("a1", "ab2", "a3", "ab4", "a5", "ab6", "a7", "ab8", "a9"));
/**
*報錯
*java.util.ConcurrentModificationException
*/
for (String str : list) {
if (str.contains("b")) {
list.remove(str);
}
*報錯:下标越界
*java.lang.IndexOutOfBoundsException
int size = list.size();
for (int i = 0; i < size; i++) {
String str = list.get(i);
list.remove(i);
*正常删除,每次調用size方法,損耗性能,不推薦
for (int i = 0; i < list.size(); i++) {
*
正常删除,推薦使用for (Iterator ite = list.iterator(); ite.hasNext();) {
String str = ite.next();
ite.remove();
報異常IndexOutOfBoundsException我們很了解,是動态删除了元素導緻數組下标越界了。
那ConcurrentModificationException呢?
其中,for(xx in xx)是增強的for循環,即疊代器Iterator的加強實作,其内部是調用的Iterator的方法,為什麼會報ConcurrentModificationException錯誤,我們來看下源碼
取下個元素的時候都會去判斷要修改的數量和期待修改的數量是否一緻,不一緻則會報錯,而通過疊代器本身調用remove方法則不會有這個問題,因為它删除的時候會把這兩個數量同步。搞清楚它是增加的for循環就不難了解其中的奧秘了。