Junior — Middle
What situations can lead to a ConcurrentModificationException in a single-threaded environment?
sobes.tech AI
Answer from AI
The ConcurrentModificationException in Java usually occurs when a collection is modified concurrently during iteration. In a single-threaded environment, this can happen if you modify the collection directly (for example, calling add(), remove() methods on the collection itself, rather than through the iterator) while iterating over it.
Example:
List<String> list = new ArrayList<>(Arrays.asList("a", "b", "c"));
for (String s : list) {
if (s.equals("b")) {
list.remove(s); // Direct modification of the collection during iteration
}
}
// This will throw a ConcurrentModificationException
The correct way to remove elements during iteration is to use the iterator's methods:
Iterator<String> iterator = list.iterator();
while (iterator.hasNext()) {
String s = iterator.next();
if (s.equals("b")) {
iterator.remove(); // Safe removal
}
}