Java Program to Implement CopyOnWriteArraySet API Last Updated : 30 Sep, 2022 Comments Improve Suggest changes Like Article Like Report CopyOnWriteArraySet is a member of the Java Collections Framework. It is a Set that uses an internal CopyOnWriteArrayList for all of its operations. It was introduced in JDK 1.5, we can say that it is a thread-safe version of Set. To use this class, we need to import it from java.util.concurrent package. Implementation: Example Java // Java Program to Implement CopyOnWriteArraySet API // Importing required utility classes // from java.util package import java.util.Collection; import java.util.HashSet; import java.util.Iterator; import java.util.Set; import java.util.concurrent.CopyOnWriteArraySet; // CopyOnWriteArraySetImpl public class<E> GFG { private CopyOnWriteArraySet<E> copyOnWriteArraySet; // Constructor of this class public GFG() { // Creating an empty set copyOnWriteArraySet = new CopyOnWriteArraySet<E>(); } // Creates a set containing all of the elements // of the specified collection public GFG(Collection<? extends E> c) { copyOnWriteArraySet = new CopyOnWriteArraySet<E>(c); } // Method // To add the specified element into list // if not already present public boolean add(E eobj) { return copyOnWriteArraySet.add(eobj); } // Method // Returning true if there is a specified element // present in the list public boolean contains(Object obj) { return copyOnWriteArraySet.contains(obj); } // Method // Returning true if the set is empty public boolean isEmpty() { return copyOnWriteArraySet.isEmpty(); } // Method // To traverse over the elements // present in the set public Iterator<E> iterator() { return copyOnWriteArraySet.iterator(); } // Method // To remove the specified element // present in the Set public boolean remove(Object obj) { return copyOnWriteArraySet.remove(obj); } // Method // Returning the number of elements // present in the set public int size() { return copyOnWriteArraySet.size(); } // Method // Removing all elements from the given set public void clear() { copyOnWriteArraySet.clear(); } // Method // Returning an array containing all of the elements // present in this set public Object[] toArray() { return copyOnWriteArraySet.toArray(); } // Method // Now, adding all of the elements in the specified // collection to this set if they're not already present public boolean addAll(Collection<? extends E> c) throws UnsupportedOperationException, ClassCastException, NullPointerException, IllegalArgumentException { return copyOnWriteArraySet.addAll(c); } // Method // Returns only the elements in this set that are // contained in the specified collection public boolean retainAll(Collection<?> c) throws UnsupportedOperationException, ClassCastException, NullPointerException { return copyOnWriteArraySet.retainAll(c); } // Method // Removes from this set the elements that are contained // in the specified collection public boolean removeAll(Collection<?> c) throws UnsupportedOperationException, NullPointerException, ClassCastException { return copyOnWriteArraySet.retainAll(c); } // Returns an array containing all of the elements in // this set. public <T> T[] toArray(T[] a) throws ArrayStoreException, NullPointerException { return copyOnWriteArraySet.toArray(a); } // Method // Main driver Method public static void main(String args[]) { // Creating an object of above class (GFG class) // Declaring object of integer type GFG<Integer> copyOnWriteArraySet = new GFG<Integer>(); // Adding custom input elements after condition // check // Custom input elements are added // using the add() method if (copyOnWriteArraySet.add(12)) System.out.println("Element 12 added to Set"); if (copyOnWriteArraySet.add(13)) System.out.println("Element 13 added to Set"); if (copyOnWriteArraySet.add(14)) System.out.println("Element 14 added to Set"); if (copyOnWriteArraySet.add(15)) System.out.println("Element 15 added to Set"); // Print and display the current size of Set System.out.println( "The size of copyOnWriteArraySet is " + copyOnWriteArraySet.size()); // Checking whether the Set contains element // using the contains() method if (copyOnWriteArraySet.contains(14)) System.out.println( "The copyOnWriteArraySet contains 14"); else System.out.println( "The copyOnWriteArraySet does not contain 14"); // Removing element from the Set // using remove() method if (copyOnWriteArraySet.remove(13)) // Print desired element is removed System.out.println("Element 13 removed"); else // Print desired element is not removed System.out.println("Element 13 not removed"); // Now, print and display the elements System.out.println( "The element of copyOnWriteArraySet are"); Iterator<Integer> iterator = copyOnWriteArraySet.iterator(); // Condition holds true till there is // single element remaining while (iterator.hasNext()) { // Print and display all elements size System.out.print(iterator.next() + "\t"); } // Appending a new line for better readability System.out.println(); // Creating an object of Set class of integer type Set<Integer> removedSet = new HashSet<Integer>(); // Custom input entries to above Set removedSet.add(12); removedSet.add(13); // Display message only System.out.println("The elements after removing"); // removeAll() method wipes off all elements // that was present in Set object copyOnWriteArraySet.removeAll(removedSet); // Iterator to traverse the elements Iterator<Integer> riterator = copyOnWriteArraySet.iterator(); // Again condition holds true till there is // single element remaining in the List while (riterator.hasNext()) { // Printing the elements in the object // using the next() method System.out.print(riterator.next() + "\t"); } // New line System.out.println(); // Removing all elements from the Set using clear() // method copyOnWriteArraySet.clear(); // Display message to showcase all elements are // removed System.out.println( "copyOnWriteArraySet Elements are completely removed"); // Lastly, verifying whether the Set is empty or not if (copyOnWriteArraySet.isEmpty()) // Print statement if no elements in Set System.out.println( "copyOnWriteArraySet is empty"); else // Print statement if elements found in Set System.out.println( "copyOnWriteArraySet is not empty"); } } Output: Element 12 added to Set Element 13 added to Set Element 14 added to Set Element 15 added to Set The size of copyOnWriteArraySet is 4 The copyOnWriteArraySet contains 14 Element 13 removed The element of copyOnWriteArraySet are 12 14 15 The elements after removing 12 copyOnWriteArraySet Elements are completely removed copyOnWriteArraySet is empty Comment More infoAdvertise with us Next Article Java Program to Implement CopyOnWriteArraySet API P pranaythanneru Follow Improve Article Tags : Java Java Programs Java-Collections Java-CopyOnWriteArraySet Practice Tags : JavaJava-Collections Similar Reads Program to convert Array to Set in Java Array is a group of like-typed variables that are referred to by a common name. An array can contain primitives data types as well as objects of a class depending on the definition of the array. In the case of primitives data types, the actual values are stored in contiguous memory locations. In cas 7 min read How to Implement a Thread-Safe Resizable Array in Java? Multiple threads may securely execute operations like insertion and deletion without risking data corruption when utilizing a thread-safe resizable array. The ArrayList class is a popular Java class, yet it is not thread-safe by default. We may use concurrent collections or synchronization to make i 2 min read How to Convert ArrayList to HashSet in Java? ArrayList: In Java, ArrayList can have duplicates as well as maintains insertion order. HashSet: HashSet is the implementation class of Set. It does not allow duplicates and uses Hashtable internally. There are four ways to convert ArrayList to HashSet : Using constructor.Using add() method by itera 3 min read Deep Copy of a HashSet in Java HashSet is used to store a unique set of values in Java. It is a class that stores values and provides efficient access. As we know Java uses call-by-reference. So, if we copy a Set and want to make changes to the copied Set, we want it to not affect the element of the original Set. But if it is a s 2 min read How to clone an ArrayList to another ArrayList in Java? The clone() method of the ArrayList class is used to clone an ArrayList to another ArrayList in Java as it returns a shallow copy of its caller ArrayList. Syntax: public Object clone(); Return Value: This function returns a copy of the instance of Object. Below program illustrate the Java.util.Arra 2 min read How to Make a Deep Copy of Java ArrayList? The Advantage of ArrayList is it can be defined without giving a predefined size. But the disadvantage is it is more expensive to create and maintain. To have the solution for these expenses we can create a deep copy of an ArrayList. There are two types of copies that can be made the first one is a 3 min read How to Serialize ArrayList in Java? ArrayList is a class under the collections framework of java. It is present in java.util package. An ArrayList is a re-sizable array in java i.e., unlike an array, the size of an ArrayList can be modified dynamically according to our requirement. Also, the ArrayList class provides many useful method 2 min read How to Copy or Append HashSet to Another HashSet in Java? HashSet is used to store distinct values in Java. HashSet stores the elements in random order, so there is no guarantee of the elements' order. The HashSet class implements the Set interface, backed by a hash table which is actually a HashMap instance. We can copy or append a HashSet to another Hash 4 min read How to Implement a Generic Deep Copy Method for Multidimensional Arrays in Java? In Java, two types of copies can be made of any data structure that are Deep copy and Shallow copy. When we make a deep copy of an array, the array is assigned a new memory space, and the content is copied into the new memory space. This means that if we make changes in any of the two arrays it will 3 min read How to Clone a 2D Array With Different Row Sizes in Java? 2D arrays are two-dimensional arrays. These are the simplest forms of multidimensional arrays. Java provides various methods to clone the arrays, but when dealing with 2D arrays having varying sizes, then the process becomes more difficult. Here, we will see different methods to clone 2D arrays with 5 min read Like