The CopyOnWriteArrayList iterator method returns an iterator over the elements in the sequence they were inserted.
As explained in the previous posts, CopyOnWriteArrayList creates its copy when performing any element changing operations, hence the iterator returned in the CopyOnWriteArrayList iterator method is the snapshot of the state of the list when the iterator was constructed.
remove method is not supported by the iterator. An java.lang.UnsupportedOperationException is thrown if remove() is called on the iterator.
In the below code we will see how to iterate over the CopyOnWriteArrayList, and also see what happens when we call the remove() on the iterator.
Sample Code
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 |
package com.kscodes.collections.samples; import java.util.Iterator; import java.util.concurrent.CopyOnWriteArrayList; public class CopyOnWriteArrayListIteratorEx { public static void main(String[] args) { // Create a copyOnWriteArrayList object CopyOnWriteArrayList<String> copyOnWriteArrayList = new CopyOnWriteArrayList<>(); // Adding 4 elements using add() method copyOnWriteArrayList.add("Zero"); copyOnWriteArrayList.add("One"); copyOnWriteArrayList.add("Two"); copyOnWriteArrayList.add("Three"); // Use the iterator to print all the elements System.out.println("Use the iterator to print all the elements"); Iterator<String> iterator = copyOnWriteArrayList.iterator(); while(iterator.hasNext()){ System.out.println(iterator.next()); } // Try remove method on the iterator and see what happens System.out.println("Try remove method on the iterator and see what happens"); iterator = copyOnWriteArrayList.iterator(); while(iterator.hasNext()){ iterator.remove(); } } } |