we can do remove operation in ArrayList while iterating then Why we can't do the same operation CopyOnWriteArrayList while iterating?
why UnsupportedOperationException occurs during this process?
we can do remove operation in ArrayList while iterating then Why we can't do the same operation CopyOnWriteArrayList while iterating?
why UnsupportedOperationException occurs during this process?
All mutators (add, remove etc...) of CopyOnWriteArrayList
are just creating new array and iterator()
just create an Iterator
with a snapshot of the array to exclude the possibility of interference, the docs:
The "snapshot" style iterator method uses a reference to the state of the array at the point that the iterator was created. This array never changes during the lifetime of the iterator, so interference is impossible and the iterator is guaranteed not to throw ConcurrentModificationException.
The definition of CopyOnWriteArrayList per the Java Doc:
A thread-safe variant of ArrayList in which all mutative operations (add, set, and so on) are implemented by making a fresh copy of the underlying array.
The key point to note here is "fresh copy". The iterator() method uses a reference to the state of the array at the point that the iterator was created. The iterator will not reflect additions, removals, or changes to the list since the iterator was created. Thus the copy iterator has might be outdated but as definition states remove() method needs fresh copy. That's why add(), set() and remove() methods of Iterator in CopyOnWriteArrayList throw UnsupportedOperationException.