Prevent / Solve java.util.ConcurrentModificationException

Your program throws ConcurrentModificationException while running and how can you prevent / solve it

It happens when your program removing an item in an ArrayList, Collection or List while looping (iterating) over it.
Example:


for (int i = 0; i < yourArrayList.size(); i++) {
	if (yourArrayList.get(i).compareToIgnoreCase("apple") == 0) {
		yourArrayList.remove(i);
	}
}

//Exception in thread "main" java.util.ConcurrentModificationException
//	at java.util.AbstractList$Itr.checkForComodification(Unknown Source)
//	at java.util.AbstractList$Itr.next(Unknown Source)

To prevent this, there are several solutions depending on you program logic.

Solution 1 – Using the java.util.Iterator:

import java.util.Iterator;

...

Iterator<String> iterator = yourArrayList.iterator();
		
while (iterator.hasNext()) {
	String string = (String) iterator.next();
	
	if (string.compareToIgnoreCase("apple") == 0) {
		iterator.remove();
	}			
}

Solution 2 – Using an temporary ArrayList to store items for removal:

//Initialize an temporary array list with similar type
ArrayList<String> itemToRemove = new ArrayList<String>();

//Search for items matching string "apple"
for (int i = 0; i < yourArrayList.size(); i++) {
	if (yourArrayList.get(i).compareToIgnoreCase("apple") == 0) {
		itemToRemove.add(yourArrayList.get(i));		
	}
}

//Remove items stored in itemToRemove ArrayList
yourArrayList.removeAll(itemToRemove);

Hope it helps.