2014-02-06 37 views
0

在我的代碼:ConcurrentModificationException的在foreach循環

Collection<String> c = new ArrayList<>(); 
    Iterator<String> it = c.iterator(); 
    c.add("Hello"); 
    System.out.println(it.next()); 

異常occures,因爲迭代器創建後,我的收藏改變。

但是,我們在此代碼:

ArrayList<Integer> list = new ArrayList<Integer>(); 
    list.add(1); 
    list.add(2); 
    list.add(3); 
    for (Integer integer : list) {  // Exception is here 
     if (integer.equals(2)) { 
      list.remove(integer); 
     } 
    } 

爲什麼出現異常?

在第二個代碼中,我在for-each循環之前在我的集合中進行了更改。

+1

你什麼事remove()不,如果不修改集合刪除元素? –

+0

for-each使用迭代器。 – kosa

+0

這個問題似乎是無關緊要的,因爲它沒有顯示任何先前的研究 – njzk2

回答

4

在第二個循環中,這是相同的原因 - 您要從列表中刪除元素。

要從List同時通過其循環刪除元素,無論是使用標準的老式的for循環:

for(int i=0;i<list.size();i++) { 

,並刪除循環內列表項或使用ListIterator遍歷列表。

1

您也正在改變中的集合for-each循環:

list.remove(integer); 

如果您需要刪除在迭代的元素,你要麼跟蹤您需要刪除,後爲刪除索引的 - 循環結束,或者使用允許同時修改的Collection。

0

這裏的,如果你需要刪除元素,同時使用更好的語法迭代來從來沒有得到ConcurrentModificationExceptions最徹底的方法:

// utility method somewhere 
public static <T> Iterable<T> remainingIn(final Iterator<T> itT) { 
    return new Iterable<T>() { 
     @Override 
     public Iterator<T> iterator() { 
      return itT; 
     } 
    } 
} 

// usage example 
Iterator<Integer> itI = list.iterator(); 
for (Integer integer : remainingIn(itI)) { 
    if (integer.equals(2)) { 
     itI.remove(); 
    } 
} 
0

你也可以使用CopyOnWriteArrayList,這是不是很有效,但解決了ConcurrentModificationException,並且你可以安全使用刪除方法。

1

異常是因爲你迭代以及從列表

for (Integer integer : list) {  // Exception is here because you are iterating and also removing the elements of same list here 
     if (integer.equals(2)) { 
      list.remove(integer); 
     }