Should not the answer be E as a RuntimeException (UnsupportedOperationException) would be thrown?
From the explanation:
D is correct.
A CopyOnWriteArrayList allows modifications while being iterated with an Iterator because the iteration happens on a reference of the List that reflects how it was when the Iterator was originated, which is why B is incorrect.
From CopyOnWriteArrayList javadoc:
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 iterator will not reflect additions, removals, or changes to the list since the iterator was created. Element-changing operations on iterators themselves (remove, set, and add) are not supported. These methods throw UnsupportedOperationException.
Daniel Clinton wrote:Should not the answer be E as a RuntimeException (UnsupportedOperationException) would be thrown?
No! The correct answer and the explanation in the mock exam are spot-on. And the best way to illustrate is of course to run the program and see what happens. So here we go
Here's the code from the mock question (I added 100 elements to the list as the comment suggests)And here is a class invoking the work() method on a ConcurrentModificator instanceOutput: 200 (and that's why answer D is correct)
And if you read the fragment you quoted from the CopyOnWriteArrayList javadoc carefully, you'll see that's exactly what's described: additions to the list since the iterator was created, are not reflected. When do you get a runtime UnsupportedOperationException? If you perform element-changing operations on the iterator itself, but on line1 you are (obviously) adding elements to the list using the list itself (reference variable list) and not the iterator (reference variable it). So if you would change line1 to it.remove();, you'll get a runtime UnsupportedOperationException.