Java – how to avoid concurrentmodificationexception when iterating over this collection?

I need to iterate over a series of projects & sometimes added to the collection at the same time However, if I add it during an iteration, I just start the iteration by breaking through the iteration loop Start the iteration from scratch However, this led to

List<Integer> collection = new ArrayList<>();
    for (Integer lobId: collection) {
         ..
         if (someCondition) {
             collection.add(something); 
             break; 
         }
    }

How can I do the above to avoid concurrent modificationexception?

Is it correct to simply use array instead of ArrayList to avoid this exception? Is there any kind of special collection here?

Edit:

I don't want to create a new copy of this ArrayList because I will repeat the entire iteration several times unless some requirements are completed Every time I create a new copy, it will bring some extra overhead. If possible, I want to avoid it

If possible, I want to maintain a sort order & unique values in the set Is there anything that can be used in any library? Otherwise, I can sort them at the end of the iteration & remove duplicates It's no problem for me

Solution

This code cannot cause concurrentmodificationexception, because after you add an element, you break the loop and no longer use the iterator

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>