Java CopyOnWriteArrayList Methods Example

In this source code example, we will show you the usage of important Java CopyOnWriteArrayList class methods with examples.

The CopyOnWriteArrayList is a thread-safe variant of ArrayList in which all modifications (add, set, and so on) are implemented by making a fresh copy. It's useful in scenarios where you have far more iterations than modifications and you need to prevent thread interference and memory consistency errors.

Java CopyOnWriteArrayList Methods Example

import java.util.List;
import java.util.Iterator;
import java.util.concurrent.CopyOnWriteArrayList;

public class CopyOnWriteArrayListDemo {
    public static void main(String[] args) {
        // 1. Initialization
        List<String> cowList = new CopyOnWriteArrayList<>();
        System.out.println("Initialized list: " + cowList);

        // 2. Adding elements
        cowList.add("Apple");
        cowList.add("Banana");
        cowList.add("Cherry");
        System.out.println("After adding elements: " + cowList);

        // 3. Remove an element
        cowList.remove("Banana");
        System.out.println("After removing Banana: " + cowList);

        // 4. Iterate over the list
        Iterator<String> iterator = cowList.iterator();
        while (iterator.hasNext()) {
            System.out.println(iterator.next());
        }

        // 5. Add element during iteration
        for (String item : cowList) {
            if ("Apple".equals(item)) {
                cowList.add("Dragonfruit");
            }
            System.out.println(item);
        }

        System.out.println("After adding Dragonfruit during iteration: " + cowList);
    }
}

Output:

Initialized list: []
After adding elements: [Apple, Banana, Cherry]
After removing Banana: [Apple, Cherry]
Apple
Cherry
Apple
Cherry
After adding Dragonfruit during iteration: [Apple, Cherry, Dragonfruit]

Explanation:

1. An empty CopyOnWriteArrayList of type String is initialized.

2. Elements are added to the list using the add method.

3. The remove method is used to delete the string "Banana" from the list.

4. The Iterator is used to traverse and print each element of the list.

5. The special feature of CopyOnWriteArrayList is demonstrated: it allows modifications like add during iteration without ConcurrentModificationException. As we iterate through the list, we add "Dragonfruit" when we encounter "Apple".


Comments