Intellipaat Back

Explore Courses Blog Tutorials Interview Questions
0 votes
in Java by (3.4k points)
edited by

We all know you can't do this:

for (Object i : l) { if (condition(i)) { l.remove(i); } }

ConcurrentModificationException etc... this apparently works sometimes, but not always. Here's some specific code:

public static void

main(String[] args)

{ Collection<Integer> l = new ArrayList<>();

for (int i = 0; i < 10; ++i)

{ l.add(4); l.add(5); l.add(6); }

for (int i : l)

{ if (i == 5) { l.remove(i); }




This, of course, results in:

Exception in thread "main" java.util.ConcurrentModificationException

... even though multiple threads aren't doing it... Anyway.

What's the best solution to this problem? How can I remove an item from the collection in a loop without throwing this exception?

I'm also using an arbitrary Collection here, not necessarily an ArrayList, so you can't rely on get.


1 Answer

0 votes
by (2k points)

The safest and best way to solve your issue is to use Iterator.remove() as it performs the assigned action for each remaining element until all elements have been processed or the action throws an exception. Exceptions thrown by the action are sent to the caller.

The role of an iterator is undefined if the action alternates the collection in any way (even by calling the remove method or other mutator methods of Iterator subtypes) except an overriding class has specified a joint alteration policy.

Here’s what you need to use:

List<String> list = new ArrayList<>(); 

// This is a clever way to create the iterator and call iterator.hasNext() like 

// you would do in a while-loop. It would be the same as doing:

 // Iterator<String> iterator = list.iterator(); 

// while (iterator.hasNext()) 


 for (Iterator<String> iterator = list.iterator(); iterator.hasNext();)


 String string =; if (string.isEmpty()) 

{ // Eliminate the current component from the iterator and the list. iterator.remove(); } 


Browse Categories