How to avoid ConcurrentModificationException while iterating this collection?

collections, exception, guava, java

Solution

This code cannot lead to ConcurrentModificationException because after you add an element you break the loop and dont use iterator anymore

Problem

I need to iterate over a collection of items & sometimes add to that collection at the same time. However, incase I add while iterating then I just start the iteration from fresh by breaking out of iteration loop & restarting iteration from beginning. However this leads to `ConcurrentModificationException`. [code below] ``` List<Integer> collection = new ArrayList<>(); for (Integer lobId: collection) { .. if (someCondition) { collection.add(something); break; } } ``` How could I possibly do something like above avoiding `ConcurrentModificationException`? Would it be correct to simply use an `Array` instead of `ArrayList` to avoid this exception ? Is there any type of specialized collection for this ? -- Edit: I dont want to create a new copy for this arraylist because I'm repeating this entire iteration process multiple times unless some requirement is completed. Creating a new copy each time would bring in some extra overhead, which I would like to avoid if somehow possible. Also if possible I would like to maintain a sorted order & unique values in that collection. Is there anything that is ready to use in any library? Otherwise I could sort it at the end of iteration process & remove duplicates. That will also do fine for me.

Original source

Related problems