2
package com.test;

import java.util.ArrayList;
import java.util.Iterator;

public class TestList {

    public static void main(String[] args) {

        ArrayList<String> list = new ArrayList<>();
        list.add("One");
        list.add("Two");
        list.add("Three");
        list.add("Four");

        Iterator<String> it = list.iterator();
        while (it.hasNext()) {
            String str = it.next();
            System.out.print(str + " ");
            if (str.equals("Three")) {
                list.remove("Three");
            }
        }
        System.out.println();
        System.out.println("List are :" + list);
    }
}

Output : One Two Three List are :[One, Two, Four]

Why it is not throwing ConcurrentModificationException ?

However ConcurrentModificationException is thrown for following scenarios :

if (str.equals("One")) {
                list.remove("One");
        }

        if (str.equals("Two")) {
                list.remove("Two");
        }

        if (str.equals("Four")) {
                list.remove("Four");
        }
  • It’s a known bug, and oracle deliberately chose not to fix it because fixing it might change behaviour of existing code. I’ll see if I can find link – cpp beginner Oct 28 '17 at 17:45

0 Answers0