CopyOnWriteArraySet removeAll() method in Java with Examples
Last Updated :
10 May, 2019
The removeAll() method of CopyonWriteArraySet method removes all the elements of this CopyOnWriteArraySet that are present in the specified collection. That means elements which are common in both the collections are removed from this CopyOnWriteArraySet.
Syntax:
public boolean removeAll(Collection<E> c)
Parameters: This method accepts a parameter c which is the collection containing elements to be removed from this set.
Return Value: This method returns a boolean value such as true, if the CopyOnWriteArraySet is changed. Else this method returns false.
Exceptions: This method throws following Exceptions:
- ClassCastException: if the class of an element of this set is incompatible with the specified collection
- NullPointerException: if this set contains a null element and the specified collection does not permit null elements, or if the specified collection is null.
Below program illustrates the removeAll() function of CopyOnWriteArrayList class:
Program 1:
import java.util.concurrent.CopyOnWriteArraySet;
import java.util.*;
public class GFG {
public static void main(String[] args)
{
CopyOnWriteArraySet<Integer> ArrSet
= new CopyOnWriteArraySet<Integer>();
ArrSet.add( 10 );
ArrSet.add( 20 );
ArrSet.add( 30 );
ArrSet.add( 50 );
System.out.println( "CopyOnWriteArraySet: "
+ ArrSet);
ArrayList<Integer> Arrlist
= new ArrayList<Integer>();
Arrlist.add( 10 );
Arrlist.add( 30 );
Arrlist.add( 40 );
System.out.println( "ArrayList: " + Arrlist);
System.out.println( "Elements removed "
+ "from CopyOnWriteArraySet: "
+ ArrSet.removeAll(Arrlist));
System.out.println( "Updated CopyOnWriteArraySet: "
+ ArrSet);
}
}
|
Output:
CopyOnWriteArraySet: [10, 20, 30, 50]
ArrayList: [10, 30, 40]
Elements removed from CopyOnWriteArraySet: true
Updated CopyOnWriteArraySet: [20, 50]
Program 2: To show NullpointerException
import java.util.concurrent.CopyOnWriteArraySet;
import java.util.*;
public class GFG {
public static void main(String[] args)
{
CopyOnWriteArraySet<Integer> ArrSet
= new CopyOnWriteArraySet<Integer>();
ArrSet.add( 10 );
ArrSet.add( 20 );
ArrSet.add( 30 );
ArrSet.add( 50 );
System.out.println( "CopyOnWriteArraySet: "
+ ArrSet);
try {
System.out.println( "Elements removed "
+ "from CopyOnWriteArraySet: "
+ ArrSet.removeAll( null ));
}
catch (Exception e) {
System.out.println(e);
}
}
}
|
Output:
CopyOnWriteArraySet: [10, 20, 30, 50]
java.lang.NullPointerException
Share your thoughts in the comments
Please Login to comment...