The removeAll() method of Java AbstractSet class is used to remove from this set all of its elements that are contained in the specified collection.
public boolean removeAll(Collection c)
Parameters: This method takes collection c as a parameter containing elements to be removed from this set.
Returns Value: This method returns true if this set changed as a result of the call.
Exception: The method throws three types of exception:
- UnsupportedOperationException – This is thrown if the operation is not supported by this set.
- ClassCastException – This is thrown when the class of an element of this set is not compatible with the specified collection.
- NullPointerException – This is thrown when this set contains a null element and the specified collection does not permit null elements, or if the collection is null.
Below are the examples to illustrate the removeAll() method.
AbstractSet before removeAll() operation : [1, 2, 3, 4, 5] Collection Elements to be removed : [1, 2, 3] AbstractSet after removeAll() operation : [4, 5]
Example 2: For NullPointerException
AbstractSet before removeAll() operation : [1, 2, 3, 4, 5] Collection Elements to be removed : null Exception thrown : java.lang.NullPointerException
Attention reader! Don’t stop learning now. Get hold of all the important Java Foundation and Collections concepts with the Fundamentals of Java and Java Collections Course at a student-friendly price and become industry ready.