Java CopyOnWriteArraySet Methods Example

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

Common Methods of CopyOnWriteArraySet

import java.util.Set;
import java.util.Iterator;
import java.util.concurrent.CopyOnWriteArraySet;

public class CopyOnWriteArraySetDemo {
    public static void main(String[] args) {
        // 1. Initialization
        Set<String> cowSet = new CopyOnWriteArraySet<>();
        System.out.println("Initialized set: " + cowSet);

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

        // 3. Check for a specific element
        System.out.println("Contains 'Apple'? " + cowSet.contains("Apple"));

        // 4. Remove an element
        cowSet.remove("Banana");
        System.out.println("After removing 'Banana': " + cowSet);

        // 5. Iterate over the set
        Iterator<String> iterator = cowSet.iterator();
        while (iterator.hasNext()) {
            System.out.println(iterator.next());
        }

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

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

Output:

Initialized set: []
After adding elements: [Apple, Banana, Cherry]
Contains 'Apple'? true
After removing 'Banana': [Apple, Cherry]
Apple
Cherry
Apple
Cherry
After adding 'Dragonfruit' during iteration: [Dragonfruit, Apple, Cherry]

Explanation:

1. An empty CopyOnWriteArraySet of type String is initialized.

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

3. The contains method checks if a particular element exists in the set.

4. The remove method is used to delete the string "Banana" from the set.

5. The Iterator is used to traverse and print each element of the set.

6. The special feature of CopyOnWriteArraySet is demonstrated: it allows modifications like add during iteration without ConcurrentModificationException.

7. As we iterate through the set, we add "Dragonfruit" when we encounter "Apple".


Comments