UnsupportedOperationException while iterating over CopyOnWriteArrayList

skip :

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?

Mureinik :

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 UpsupportedOperationException
}

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=115656&siteId=1