ahaneo
ahaneo

Reputation: 187

modify a list map getting ConcurrentModificationException

Hi I am creating two lists to hold good and bad data values. I pass these lists to a method where I add a new key value to the goodMap, check some conditions on the record if it is not good then add that record to the bad file and remove it from the good File ,but I recieve oncurrentModificationException while doing so. How do i Fix this?

Pseudocode

    //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;

    }

Upvotes: 0

Views: 274

Answers (2)

gaurav
gaurav

Reputation: 3116

Otherwise you can also use ConcurrentHashMap(),instead of hashMap ,It won't give you concurrentmodificationexception at the time of removing the elements when you iterate.

Upvotes: 0

ewan.chalmers
ewan.chalmers

Reputation: 16235

Instead of doing this:

_temp1.remove(_Record);

try doing this:

i.remove();

See the javadoc for Iterator.remove.

Upvotes: 8

Related Questions