When you first start writing in Java, one of the first mistakes that beginners face is a terrible beast with a long name: ConcurrentModificationException. This error looks scary, but the reason for it is trivial. Let's figure out why it occurs and how to avoid it.

What's going on?
List<String> names = new ArrayList<>();
names.add("Anya");
names.add("Boris");
names.add("Vika");
for (String name : names) {
if (name.equals("Vika")) {
names.remove(name); // 💥 ConcurrentModificationException!
}
}But instead of a result, you get an exception.
🤛 Why is this happening?
Because for-each uses iterator inside, and you are changing the list itself at this time. It's like you're walking across a bridge, and someone's dismantling the boards behind you. JVM is like: "STOP! It's not safe!" 🚨
🔍 How to understand what exactly causes the error
list.remove()insidefor-eachmap.put()insideforbymap.entrySet()Modification through a collection inside
Stream
✅ How to do it right
🛠 Method 1: Use a regular for
for (int i = 0; i < names.size(); i++) {
if (names.get(i).equals("Vika")) {
names.remove(i);
i--;
}
}🛠 Method 2: Use Iterator
Iterator<String> it = names.iterator();
while (it.hasNext()) {
if (it.next().equals("Vika")) {
it.remove();
}
}🛠 Method 3: Use removeIf
names.removeIf(name -> name.equals("Vika"));🤯 Why Juns often make mistakes
❌ They don't know that
for-eachusesIteratorinside❌ Confused
remove()in the collection and in the iterator❌ They are afraid to use
Iteratorbecause it seems "old"❌ They don't read the trace stack carefully
💬 How it sounds in the interview
— Why do you have
ConcurrentModificationExceptionin your code?
— I just deleted the element insidefor-each...
ConcurrentModificationException is not a bug, it is protection against potentially dangerous behavior. And if you caught it — rejoice! You are now one step closer to understanding Java at a deep level 🧩
📚 Do you want to delve into the topic?
In the attachment Code you will find detailed lessons on CMake and C++, step-by-step exercises, error analysis and convenient practice right on your phone or browser.
And if you want to be aware of the news, new features and useful materials - subscribe to our Telegram channel. It's cozy, businesslike and with love for code ❤️
