I came across the following statement in a book:
Any mutating methods called on a copy-on-write-based
Iterator
orListIterator
(such as add, set or remove) will throw anUnsupportedOperationException
.
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?
You're calling
remove
on the list itself, which is fine. The documentation states that callingremove
on the list's iterator would throw anUpsupportedOperationException
. E.g.: