2011-04-13 45 views
6

這裏是我的代碼:與 「java.util.ConcurrentModificationException」 卡殼

// eventList is a LinkedList 

public void run() { 

    Iterator<Event> it = eventList.iterator(); 
    int size = eventList.size(); 

    while(size > 0) { 
     while(it.hasNext()) { 
      Event e = it.next(); //flaged line 

      if(e.ready()) { 
       System.out.println(e); 
       e.action(); 
       eventList.remove(e); 
       --size; 
      } 
     } 
    } 
} 

錯誤java.util.ConcurrentModificationException在林立的標誌(Event e = it.next();)被拋出。你是否看到我的代碼中有一個錯誤,使得該異常被拋出的原因顯而易見?

+0

可能重複的[刪除列表上的循環](http://stackoverflow.com/questions/1921104/loop-on-list-with-remove) – McDowell 2011-05-09 12:09:15

回答

17

正在修改eventList,同時使用eventList.remove()進行迭代。您不得這樣做,否則Iterator將無法​​使用。

只需將eventList.remove(e)替換爲it.remove()即可,應該沒問題。

此外,您還可以輕鬆地運行到一個無限循環,如果你的一個事件是不是準備在第一次運行,因爲it.hasNext()不會返回true一旦返回false,但size將不能修改。一種解決方案是將整個Iterator it = ...內部的第一個while循環。

我也修改外部while循環使用while (!e.isEmpty())而不是試圖手動跟蹤eventList的大小。

+0

+1這個答案;只是一個說明,這個問題描述在該例外的文檔中: http://download.oracle.com/javase/6/docs/api/java/util/ConcurrentModificationException.html – 2011-04-13 07:35:27

+0

謝謝。我認爲問題在於我在代碼上花費了很多時間:)謝謝。 – artaxerxe 2011-04-13 07:37:11

1

您應該通過迭代器移除元素,否則迭代器會因爲底層集合發生變化而重置。