简体   繁体   中英

getting rid of concurrent modification exception

i have a small problem in java. I am trying to loop through an ArrayList and add more items to the same arraylist during the looping and am getting concurrentModificationexception. what are the work-around for this problem, my code is like this

ArrayList "Errors" is already populated.

ArrayList<MainErrorObject> errors;
ArrayList<MainErrorObject> newList;

for (MainErrorObject current : errors)
{
   newList = processErrorObjects(current);
   errors.addall(newList);
}

When i try to execute the code above, i get the concurrentmodification exception. please help me in resolving this.

Thanks in advance.

you can't iterate & modify the same collection. So have a temporary ArrayList and copy the content to main list when iteration is done.

ArrayList<MainErrorObject> tempErrors;
for (meObject : Errors) {

  newList = processErrorObjects();
  tempErrors.addAll(newList);

}
errors.addAll(tempErrors);

Ps: follow the java naming conventions

You can use the Iterator class and use the add() method from Iterator , like this:

ListIterator<MainErrorObject> it = Errors.listIterator();
MainErrorObject me = null;

while(it.hasNext()) {
   me = it.next();
   if (//condition)
       it.add(item);
}

which will never throw such an exception because it's smart enough to handle said concurrent modifications.

Source: ListIterator javadocs

Use ListIterator .

To avoid java.util.ConcurrentModificationException exception, we can add an item through the iterator of list

for (ListIterator<MainErrorObject> itr = Errors.listIterator(); itr.hasNext();) {
      newList = processErrorObjects(itr.next());
      for (MainErrorObject obj : newList) {
          itr.add(obj);
      }

}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM