The removeAll() method in CopyOnWriteArrayList class that removes all the elements that are contained in the specified collection from the CopyOnArrayList object you call on.
Syntax:
public boolean removeAll(Collection collection)
Parameter: The method accepts only a single parameter collection which is to be removed from the calling object.
Return Value: This method returns a boolean value. It returns true if this remove operation is successful.
Exception: This method throws following exceptions:
- ClassCastException: if the class of an element of this list is incompatible with the specified collection.
- NullPointerException: if the specified collection is null or if this list contains a null element and the specified collection does not permit null elements.
Below examples illustrates the removeAll() method:
Example 1:
import java.util.ArrayList;
import java.util.concurrent.CopyOnWriteArrayList;
public class Demo {
public static void main(String args[])
{
CopyOnWriteArrayList<String> wishlist
= new CopyOnWriteArrayList<>();
wishlist.add( "TV" );
wishlist.add( "computer" );
wishlist.add( "play station" );
wishlist.add( "mobile" );
wishlist.add( "smart watch" );
System.out.println( "CopyOnWriteArrayList: \n"
+ wishlist);
ArrayList<String> checkList
= new ArrayList<>();
checkList.add( "play station" );
checkList.add( "TV" );
checkList.add( "mobile" );
System.out.println( "\nCollection to be removed:\n"
+ checkList);
wishlist.removeAll(checkList);
System.out.println( "\nAfter removal of collection"
+ " from CopyOnWriteArrayList:\n"
+ wishlist);
}
}
|
Output:
CopyOnWriteArrayList:
[TV, computer, play station, mobile, smart watch]
Collection to be removed:
[play station, TV, mobile]
After removal of collection from CopyOnWriteArrayList:
[computer, smart watch]
Example 2: To show NullPointerException
import java.util.ArrayList;
import java.util.concurrent.CopyOnWriteArrayList;
public class Demo {
public static void main(String args[])
{
CopyOnWriteArrayList<String> wishlist
= new CopyOnWriteArrayList<>();
wishlist.add( "TV" );
wishlist.add( "computer" );
wishlist.add( "play station" );
wishlist.add( "mobile" );
wishlist.add( "smart watch" );
System.out.println( "CopyOnWriteArrayList: \n"
+ wishlist);
ArrayList<String> checkList
= null ;
System.out.println( "\nCollection to be removed: "
+ checkList);
try {
wishlist.removeAll(checkList);
}
catch (Exception e) {
System.out.println( "\nException thrown"
+ " while removing null "
+ "from the CopyOnWriteArrayList: \n"
+ e);
}
}
}
|
Output:
CopyOnWriteArrayList:
[TV, computer, play station, mobile, smart watch]
Collection to be removed: null
Exception thrown while removing null from the CopyOnWriteArrayList:
java.lang.NullPointerException