This article is participating in “Java Theme Month – Java Debug Notes Event”, see < Event link > for more details.

This article, the original problem: translate for stackoverflow question stackoverflow.com/questions/2…

Issue an overview

We know that if this operation complains ConcurrentModificationException

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

But the following code sometimes works and sometimes fails

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);
        }
    }

    System.out.println(l);
}
Copy the code

Error message:

Exception in thread "main" java.util.ConcurrentModificationException
Copy the code

Even multithreading can’t do this. How do we remove elements from a Collection in an iterative Collection loop without ConcurrentModification?

Note that this question refers to all Collection subclasses and not to ArrayList, so you can’t answer this question with the special case of arrayList.get ()

Best answer

Iterator.remove() is fine, you can use it this way

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

// A while loop is also a clever way to iterate
// Iterator
      
        iterator = list.iterator();
      
// while (iterator.hasNext()) {
for (Iterator<String> iterator = list.iterator(); iterator.hasNext();) {
    String string = iterator.next();
    if (string.isEmpty()) {
        // Remove the current iteration elementiterator.remove(); }}Copy the code

Note that iterator.remove () is the only way to safely remove elements during iteration. Modifying elements in a Collection in an iteration by any other means is error-prone.

Similarly, if you have a ListIterator and want to add elements, you can just use ListIterator#add. To delete you should still use Iterator#remove.

The same Map#put has the same limitations described above and cannot be used during iteration.