CopyOnWriteArraySet in Java

CopyOnWriteArraySet in java internally uses CopyOnWriteArrayList. This is thread-safe version of set.

CopyOnWriteArraySet in java is used in java where we need to update the values while iterating over the loop. If we try to update the data in the normal set then we will get the exception. To fix this issue java introduces CopyOnWriteArraySet. CopyOnWriteArraySet  in java comes inside java.util.concurrent package.

Following is the example if we try to update the normal set.

Java Code
import java.util.*;

public class Main {
public static void main(String[] args) {
List<Integer> elements = Arrays.asList(32, 12, 45, 2, 56, 32, 1);
HashSet<Integer> set1 = new HashSet<Integer>(elements);

Iterator<Integer> itr = set1.iterator();
while (itr.hasNext()) {
System.out.println(itr.next());
set1.add(66);
}
}
}
Output:
32
Exception in thread “main” java.util.ConcurrentModificationException
at java.base/java.util.HashMap$HashIterator.nextNode(HashMap.java:1597)
at java.base/java.util.HashMap$KeyIterator.next(HashMap.java:1620)
at Main.main(Main.java:10)

Following are the constructors for CopyOnWriteArraySet in Java

  • public CopyOnWriteArraySet(): Creates an empty set.
  • public CopyOnWriteArraySet(Collection<? extends E> c): Creates a set containing all of the elements of the specified collection.

Let’s check the example for the above constructors:

Java Code
import java.util.*;
import java.util.concurrent.CopyOnWriteArraySet;

public class Main {
public static void main(String[] args) {

// 1. Using public CopyOnWriteArraySet()
CopyOnWriteArraySet<Integer> set1 = new CopyOnWriteArraySet<Integer>();
set1.add(23);
set1.add(65);
set1.add(54);
set1.add(22);
System.out.println(“Set1 : ” + set1);

// 2. Using public CopyOnWriteArraySet(Collection c)
List<Integer> elements = Arrays.asList(32, 12, 45, 2, 56, 32, 1);
CopyOnWriteArraySet<Integer> set2 = new CopyOnWriteArraySet<Integer>(elements);
System.out.println(“Set2 : ” + set2);
}
}
Output:
Set1 : [23, 65, 54, 22]
Set2 : [32, 12, 45, 2, 56, 1]

Let’s check the example if we try to update on CopyOnWriteArraySet:

Java Code
import java.util.*;
import java.util.concurrent.CopyOnWriteArraySet;

public class Main {
public static void main(String[] args) {
List<Integer> elements = Arrays.asList(32, 12, 45, 2, 56, 32, 1);
CopyOnWriteArraySet<Integer> set1 = new CopyOnWriteArraySet<Integer>(elements);
System.out.println(“Set: ” + set1);
System.out.println(“Iterating over set: “);
Iterator<Integer> itr = set1.iterator();
while (itr.hasNext()) {
System.out.println(itr.next());
set1.add(66);
set1.remove(56);
}

System.out.println(“final Set: ” + set1);
}
}
Output:
Set: [32, 12, 45, 2, 56, 1]
Iterating over set
32
12
45
2
56
1
final Set: [32, 12, 45, 2, 1, 66]

Following are the methods for CopyOnWriteArraySet in java

  1. boolean add(E e): Adds the specified element if it is not already present.
  2. boolean addAll(Collection<? extends E> c): Adds all of the elements in the specified collection if they’re not already present.
  3. void clear(): Removes all of the elements.
  4. boolean contains(Object o): Returns true if this set contains the specified element.
  5. boolean containsAll(Collection<?> c): Returns true if this set contains all of the elements of the specified collection.
  6. boolean equals(Object o): Compares the specified object with this set for equality.
  7. void forEach(Consumer<? super E> action): Performs the given action for each element of the Iterable until all elements have been processed or the action throws an exception.
  8. boolean isEmpty(): Returns true if this set contains no elements.
  9. Iterator<E> iterator(): Returns an iterator over the elements present in this set in the order in which these elements were added.
  10. boolean remove(Object o): Removes the specified element from this set if it is present.
  11. boolean removeAll(Collection<?> c): Removes all elements that are present in the specified collection.
  12. boolean removeIf(Predicate<? super E> filter): Removes all of the elements which satisfy the given predicate.
  13. boolean retainAll(Collection<?> c): Retains only the elements which are present in the specified collection.
  14. int size(): Returns the number of elements in this set.
  15. Spliterator<E> spliterator(): Returns a Spliterator over the elements in this set in the order in which these elements were added.
  16. Object[] toArray(): Returns an array containing all of the elements in this set.
  17. <T> T[] toArray(T[] a): Returns an array containing all of the elements in this set; the runtime type of the returned array is that of the specified array.

Following is the example of the above methods:

Java Code
import java.util.*;
import java.util.concurrent.CopyOnWriteArraySet;

public class Main {
public static void main(String[] args) {
List<Integer> elements = Arrays.asList(32, 12, 45, 2, 56, 32, 1,22,100,432,44,65);
CopyOnWriteArraySet<Integer> set1 = new CopyOnWriteArraySet<Integer>();
// 1. using add(E e)
set1.add(73);
set1.add(73);
System.out.println(“Set is: ” + set1);
// 3. using clear() >
set1.clear();
System.out.println(“Set after clear: ” + set1);

// 2. Using addAll(Collection c)
set1.addAll(elements);
System.out.println(“Updated Set is: ” + set1);
// 4. using contains(Object o)
System.out.println(“set contains(45)” + set1.contains(45));

// 5. using containsAll(Collection c)
List<Integer> list = Arrays.asList(32, 12, 45);
System.out.println(“set containsAll(32, 12, 45)” + set1.containsAll(list));

// 6. using equals(Object o)
CopyOnWriteArraySet<Integer> set2 = new CopyOnWriteArraySet<Integer>(elements);
System.out.println(“set1 equals set2” + set1.equals(set2));

// 7. using forEach(Consumer action)
System.out.print(“For Each element: “);
set1.forEach(obj -> {
System.out.print(” ” + obj);
});
System.out.println();

// 8. using isEmpty()
System.out.println(“set1 is empty : ” + set1.isEmpty());

// 9. using Iterator iterator()
System.out.print(“Iterating over set: “);
Iterator<Integer> itr = set1.iterator();
while (itr.hasNext()) {
System.out.print(” ” + itr.next());
}

// 10. using remove(Object o)
System.out.println(set1.remove(32));
System.out.println(“Updated after remove : ” + set1);

// 11. using removeAll(Collection c)
System.out.println(“set1. remove all : “+ set1.removeAll(Arrays.asList(32, 12, 45)));
System.out.println(“Updated after removeAll(32, 12, 45) : ” + set1);

// 12. using removeIf(Predicate filter) Removing odd numbers
System.out.println(“set1.removeIf(oddCondition)” + set1.removeIf(obj -> obj%2!=0));
System.out.println(“Updated after removing odd no.s: ” + set1);

// 13. using retainAll(Collection c)
System.out.println(“set1. retain all : ” + set1.retainAll(Arrays.asList(22, 100, 432, 44)));
System.out.println(“Updated after retainAll(22, 100, 432, 44) : ” + set1);

// 14. using size()
System.out.println(“set1 size: “+ set1.size());

// 15. using spliterator()
Spliterator<Integer> sptr = set1.spliterator();
System.out.println(“spliterator: ” + sptr);

// 16. using toArray()
Object arr1[] = set1.toArray();
System.out.print(“Array is : “);
for (Object object : arr1) {
System.out.print(” ” + object);
}
System.out.println();
// 17. using toArray(T[] a)
Integer intArr[] = new Integer[3];
intArr = set1.toArray(intArr);
System.out.print(“int array is: ” );
for (Integer intObj : intArr) {
System.out.print(” ” + intObj);
}
}
}
Output:
Set is: [73]
Set after clear: []
Updated Set is: [32, 12, 45, 2, 56, 1, 22, 100, 432, 44, 65]
set contains(45)true
set containsAll(32, 12, 45)true
set1 equals set2true
For Each element: 32 12 45 2 56 1 22 100 432 44 65
set1 is empty : false
Iterating over set: 32 12 45 2 56 1 22 100 432 44 65true
Updated after remove : [12, 45, 2, 56, 1, 22, 100, 432, 44, 65]
set1. remove all : true
Updated after removeAll(32, 12, 45) : [2, 56, 1, 22, 100, 432, 44, 65]
set1.removeIf(oddCondition)true
Updated after removing odd no.s: [2, 56, 22, 100, 432, 44]
set1. retain all : true
Updated after retainAll(22, 100, 432, 44) : [22, 100, 432, 44]
set1 size: 4
spliterator: java.util.Spliterators$ArraySpliterator@2db0f6b2
Array is : 22 100 432 44
int array is: 22 100 432 44

-A blog by Shwetali Khambe

Related Posts