If I modify a Collection while iterating over it using for-each loop, it gives ConcurrentModificationException
. Is there any workaround?

- 347,512
- 102
- 1,199
- 985

- 2,452
- 10
- 35
- 47
4 Answers
Use Iterator#remove
.
This is the only safe way to modify a collection during iteration. For more information, see The Collection Interface tutorial.
If you also need the ability to add elements while iterating, use a ListIterator
.

- 43,520
- 33
- 120
- 170
-
So i just create an iterator object of that collection, go through the collection using hasNext() and remove using what you suggested? Thanks. Can I also add elements? – aps Aug 05 '11 at 15:11
-
1@aps, No you cannot add elements. And yes, obtain the iterator from the collection. – mre Aug 05 '11 at 15:13
-
Add new element while loop by listIterator.next() and listIterator.add() only validate when both 'listIterator' are same object. – jean Jan 10 '12 at 06:36
One work around is to save your changes and add/remove them after the loop.
For example:
List<Item> toRemove = new LinkedList<Item>();
for(Item it:items){
if(remove){
toRemove.add(it);
}
}
items.removeAll(toRemove);

- 23,473
- 9
- 54
- 76
-
thanks.I had thought of this before. But I have quite a number of collections, so I will have to create a lot of redundant toRemove collections for every collection I have. – aps Aug 05 '11 at 15:14
A second workaround is to use a collection class whose iterators won't give the exception. For example ConcurrentLinkedQueue
, ConcurrentHashMap
and so on.
These avoid the need to throw exceptions by providing weaker models of consistency for the iterators. (Of course, you need to understand those models, and decide whether they are suitable for your application.)
They are typically a bit slower than non-concurrent collections, but faster than the synchronized collection wrappers if there is significant contention.

- 698,415
- 94
- 811
- 1,216
-
could you please elaborate? I am using LinkedList now? Will using ConcurrentLinkedList cause any disadvantages like lower performance or anything. And why doesn't it give exceptions? Is the modifications handled by the list itself? – aps Aug 05 '11 at 15:18
-
You need to read the javadocs to understand the properties of the class. (Sorry, I misread the class name ...) – Stephen C Aug 05 '11 at 15:22
If you just want to remove the element from the collection, you can use Iterator instead of Iterable.
Otherwise, what you can do is not to iterate the original collection, but first make a copy of the list. For example if your collection is a list, than you can make a new ArrayList(originaList) and iterate over that. The modification should be done to the original list.
Another alternative which maybe better for your use case, is not to use for-each but the traditional for-.

- 24,458
- 13
- 71
- 90