Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ConcurrentModificationException for ArrayList [duplicate]

I have the following piece of code:

private String toString(List<DrugStrength> aDrugStrengthList) {     StringBuilder str = new StringBuilder();         for (DrugStrength aDrugStrength : aDrugStrengthList) {             if (!aDrugStrength.isValidDrugDescription()) {                 aDrugStrengthList.remove(aDrugStrength);             }         }         str.append(aDrugStrengthList);         if (str.indexOf("]") != -1) {             str.insert(str.lastIndexOf("]"), "\n          " );         }     return str.toString(); } 

When I try to run it, I get ConcurrentModificationException, can anyone explain why it happens, even if the code is running in same thread? And how could I avoid it?

like image 360
mabuzer Avatar asked Jul 06 '10 09:07

mabuzer


People also ask

How do you overcome ConcurrentModificationException?

How do you fix Java's ConcurrentModificationException? There are two basic approaches: Do not make any changes to a collection while an Iterator loops through it. If you can't stop the underlying collection from being modified during iteration, create a clone of the target data structure and iterate through the clone.

How do you cause ConcurrentModificationException?

Class ConcurrentModificationException. This exception may be thrown by methods that have detected concurrent modification of an object when such modification is not permissible. For example, it is not generally permissible for one thread to modify a Collection while another thread is iterating over it.


2 Answers

You can't remove from list if you're browsing it with "for each" loop. You can use Iterator. Replace:

for (DrugStrength aDrugStrength : aDrugStrengthList) {     if (!aDrugStrength.isValidDrugDescription()) {         aDrugStrengthList.remove(aDrugStrength);     } } 

With:

for (Iterator<DrugStrength> it = aDrugStrengthList.iterator(); it.hasNext(); ) {     DrugStrength aDrugStrength = it.next();     if (!aDrugStrength.isValidDrugDescription()) {         it.remove();     } } 
like image 94
Konrad Garus Avatar answered Oct 13 '22 04:10

Konrad Garus


Like the other answers say, you can't remove an item from a collection you're iterating over. You can get around this by explicitly using an Iterator and removing the item there.

Iterator<Item> iter = list.iterator(); while(iter.hasNext()) {   Item blah = iter.next();   if(...) {     iter.remove(); // Removes the 'current' item   } } 
like image 23
Edward Dale Avatar answered Oct 13 '22 05:10

Edward Dale