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?
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.
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.
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 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 } }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With