The CopyOnWriteArrayList listIterator method returns a list 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 list iterator returned in the CopyOnWriteArrayList listIterator method is the snapshot of the state of the list when the iterator was constructed.
CopyOnWriteArrayList supports 2 listIterator methods
1. public ListIterator
Returns a list iterator over the elements in this list (in proper sequence).
2. public ListIterator
Returns a list iterator over the elements in this list (in proper sequence), starting at the specified position in the list.
remove/add/set methods are not supported by the list iterator. An java.lang.UnsupportedOperationException is thrown if any of these methods are called on the list iterator.
In the example below we will see how to traverse the list iterator and also see what happens when we try to use the add method on the list 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 37 38 39 40 41 42 43 |
package com.kscodes.collections.samples; import java.util.ListIterator; import java.util.concurrent.CopyOnWriteArrayList; public class COWALListIteratorEx { 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 listIterator() to print all the elements System.out.println("*****Use the listIterator() to print all the elements*****"); ListIterator<String> listIterator = copyOnWriteArrayList.listIterator(); while (listIterator.hasNext()) { System.out.println(listIterator.next()); } // Use the listIterator(int index) to print all the elements starting // from index=2 System.out.println("*****Use the listIterator(int index) to print all the elements starting from index=2*****"); ListIterator<String> listIteratorIndex = copyOnWriteArrayList.listIterator(2); while (listIteratorIndex.hasNext()) { System.out.println(listIteratorIndex.next()); } // Use the listIterator() to add a new element System.out.println("*****Use the listIterator() to add a new element*****"); ListIterator<String> listIteratorAdd = copyOnWriteArrayList.listIterator(); while (listIteratorAdd.hasNext()) { listIteratorAdd.add("New Element"); } } } |