0

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?

  • Please show the exact code in which you have the problem, and post exception stack trace – Roman Puchkovskiy Aug 26 '17 at 19:44
  • 2
    Because: http://grepcode.com/file/repository.grepcode.com/java/root/jdk/openjdk/6-b14/java/util/concurrent/CopyOnWriteArrayList.java#1036 –  Aug 26 '17 at 19:45
  • 2
    and the *why is that* is probably for a reason similar to: https://stackoverflow.com/a/28112444/180100 –  Aug 26 '17 at 19:50
  • Always read the javadocs - it's simply abiding it's contract. – Dioxin Aug 26 '17 at 19:54

1 Answers1

2

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.

Krzysztof Cichocki
  • 5,856
  • 1
  • 15
  • 31