2011-05-13 50 views
0

您好我正在創建兩個列表來保存好的和壞的數據值。 我將這些列表傳遞給一個方法,我向goodMap中添加一個新的鍵值,檢查記錄中的某些條件,如果它不好,則將該記錄添加到壞文件並將其從良好文件中刪除,但我收到oncurrentModificationException同時這樣做。我該如何解決?修改列表映射獲取ConcurrentModificationException

//original Lists of users 
    List<Map<Object, Object>> _goodFile 
    List<Map<Object, Object>> _badFile 

    //tempList to hold return value 
    List<Object> _tempList=new ArrayList<Object>(1); 



    //call the method 
    _tempList=cleanMap(_goodFile,_badFile) 

    //assign the values back to original list 
    _goodFile=_tempList.get(0); 
    _badFile=tempList.get(1); 


    //this is the method for cleaning 

    public List<Object> cleanMap (List<Map<Object, Object>> _temp1, List<Map<Object, Object>> _temp2) 

    { 

//return List 

List<Object> _returnList =new ArrayList<Object>(1); 


for (Iterator<Map<Object, Object>> i = _temp1 
        .iterator(); i.hasNext();) 

      { 
    Map<Object, Object> _Record = i.next(); 

    //first add a new key value pair to goodFile map 
    _Record.put("Key","value"); 

    // check for condition; if it is bad remove from list 

    if (bad) 
    { 
    //first add in bad file 
    _temp2.add(_Record); 

    //then remove from good file 
    _temp1.remove(_Record); 
    } 

      } 

return _returnList; 

    } 

回答

8

而不是做這個的:

_temp1.remove(_Record); 

嘗試這樣做:

i.remove(); 

查看javadoc瞭解Iterator.remove

0

否則,您也可以使用ConcurrentHashMap()而不是hashMap,它將不會在迭代時刪除元素時給出concurrentmodificationexception。