Search code examples
javacollectionsconcurrencyiteratorcopyonwritearraylist

UnsupportedOperationException while iterating over CopyOnWriteArrayList


I came across the following statement in a book:

Any mutating methods called on a copy-on-write-based Iterator or ListIterator (such as add, set or remove) will throw an UnsupportedOperationException.

But when I run the following code, it works just fine and doesn't throw the UnsupportedOperationException.

List<Integer> list = new CopyOnWriteArrayList<>(Arrays.asList(4, 3, 52));
System.out.println("Before " + list);
for (Integer item : list) {
    System.out.println(item + " ");
    list.remove(item);
}
System.out.println("After " + list);

The code above gives the following result:

Before [4, 3, 52]
4 
3 
52 
After []

Why am I not getting the exception while I am modifying the given list using the remove method?


Solution

  • You're calling remove on the list itself, which is fine. The documentation states that calling remove on the list's iterator would throw an UpsupportedOperationException. E.g.:

    Iterator<Integer> iter = list.iterator();
    while (iter.hasNext()) {
        Integer item = iter.next(); 
        System.out.println(item + " ");
        iter.remove(); // Will throw an UnsupportedOperationException
    }