Abstract set-remove all-method-in-Java-with-examples /
The removeAll() method of the Java Abstract Set class is used to remove all elements contained in the specified collection from the set.
Syntax:
public boolean removeAll(Collection c)
Parameters:This method will Collection c as a parameter containing the elements to be removed from the collection.
Return value: This method returns true if the setting changed as a result of the call.
Exceptions:This method throws three types of exceptions:
- Operation exceptions are not supported – If the operation is not supported by this setting, this exception is thrown.
- class castexception – thrown when the class of an element of this collection is incompatible with the specified collection.
- NullPointRexception – This exception is thrown when the collection contains null elements and the specified collection does not allow null elements, or if the collection is empty.
The following is an example illustrating the removeAll() method.
Program 1:
// Java program to demonstrate
// removeAll() method for Integer value
import java.util.*;
public class GFG1 {
public static void main(String[] args) throws Exception
{
try {
// Creating object of AbstractSet
AbstractSet<Integer>
abs_set = new TreeSet<Integer> ();
// Populating abs_set
abs_set .add(1);
abs_set.add (2);
>abs_set.add(3);
abs_set.add(4);
abs_set.add(5);
abs_set
System.out.println("AbstractSet before " span>
/span> abs_set);
// Creating another object of ArrayList
Collection<Integer>
span> ArrayList<Integer> ();
arrlist2.add(1);
TreeSet<Integer>();
// Populating abs_set
abs_set.add(1);
abs_set.add(2);
abs_set.add( 3);
abs_set.add(4);
abs_set. add(5);
class="c1">// print abs_set
System.out.println("AbstractSet before "
span class="o">+ abs_set);
// Creating another object of ArrayList
>Integer>
arrlist2 = new ArrayList<Integer >();
arrlist2 = null;
span>
System.out.println("Collection Elements"
+ " to be removed: "
span class="n">arrlist2);
// Removing elements from AbstractSet
// specified in arrlist2
abs_set.removeAll(arrlist2);
// print arrlist1
System.out.println("AbstractSet after "
/span> "removeAll() operation : "
>);
}
catch (NullPointerException e) {
System.out .println("Exception thrown : " + e);
}
}
}
Output:
AbstractSet before removeAll() operation : [1, 2, 3, 4, 5]
Collection Elements to be removed : null
Exception thrown : java.lang.NullPointerException
s=”p”>, 4, 5 ]
Collection Elements to be removed : null
Exception thrown : java.lang.NullPointerException