2011-12-21 10 views
2

下面是代碼:從一個ArrayList刪除元素,如果它們出現在另一個沒有提高ConcurrentModificationException的

Ledger obj = null; 
MyUtilPojo obj1 = null; 
Iterator it = toList.iterator(); 
while (it.hasNext()) { 
    obj = (Ledger) it.next(); //after first iteration next here produce an error 
    Iterator it1 = moreToList.iterator(); 
    while (it1.hasNext()) { 
     obj1 = (MyUtilPojo) it1.next(); 
     if (obj.getId() == obj1.getKey()) { 
      toList.remove(obj);         
     } 
    } 
} 

這引發錯誤ConcurrentModificationException,有人可以幫忙嗎?

+0

還看到:http://stackoverflow.com/a/4103007/180100 – 2011-12-21 05:41:18

+0

做'it.remove()' – irreputable 2011-12-21 05:45:33

回答

0

類似的東西應該工作(構建了toList新內容在一個臨時列表):在遍歷與迭代器的列表,當你修改列表中出現

final List<Ledger> target = new ArrayList<Ledger>(); 
for (final Ledger led : toList) { 
    for (final MyUtilPojo mup : moreToList) { 
     if (led.getId() != mup.getKey()) { // beware of != 
      target.add(led); 
     } 
    } 
} 

toList = target; 
0

ConcurrentModificationException的(通過添加或刪除元素)。

Ledger obj = null; 
    MyUtilPojo obj1 = null; 
    List thingsToBeDeleted = new ArrayList(); 

    Iterator it = toList.iterator(); 
    while (it.hasNext()) { 
     obj = (Ledger) it.next(); 
     Iterator it1 = moreToList.iterator(); 
     while (it1.hasNext()) { 
      obj1 = (MyUtilPojo) it1.next(); 
      if (obj.getId() == obj1.getKey()) { 
       thingsToBeDeleted.add(obj); // put things to be deleted        
      } 
     } 
    } 
    toList.removeAll(thingsToBeDeleted); 
+0

更妙的是,替換最後三行toList.removeAll(thingsToBeDeleted); – user949300 2011-12-21 05:55:45

+0

@ user949300非常真實:)。按建議修改代碼。 – sasankad 2011-12-21 06:01:11

相關問題