removeAll(Collection): This method is available in java.util.HashSet class of Java.
Syntax:
boolean java.util.AbstractSet.removeAll(Collection<?> c)
This method takes one argument. This method removes from this set all of its elements that are contained in the specified collection.
Parameters: One parameter is required for this method.
c: a collection containing elements to be removed from this set.
Returns: true if this set changed as a result of the call.
Throws:
1. UnsupportedOperationException - if the removeAll operation is not supported by this set.
2. ClassCastException - if the class of an element of this set is incompatible with the specified collection.
3. NullPointerException - if this set contains a null element and the specified collection does not permit null elements or if the specified collection is null.
Approach 1: When no exceptions
Java
import java.util.HashSet;public class HashSetremoveAll {public static void main(String[] args) {HashSet<String> hashSet = new HashSet<String>();hashSet.add("Hello");hashSet.add("Java");HashSet<String> hashSet2 = new HashSet<String>();hashSet2.add("Hello");hashSet2.add("Java");hashSet2.add("C++");hashSet2.add("Hello");hashSet2.removeAll(hashSet);System.out.println(hashSet2);}}
Output:
[C++]
Approach 2: NullPointerException
Java
import java.util.HashSet;public class HashSetremoveAll {public static void main(String[] args) {HashSet<String> hashSet = null;HashSet<String> hashSet2 = new HashSet<String>();hashSet2.add("Hello");hashSet2.add("Java");hashSet2.add("C++");hashSet2.add("Hello");hashSet2.removeAll(hashSet);System.out.println(hashSet2);}}
Output:
Exception in thread "main" java.lang.NullPointerException at java.base/java.util.Objects.requireNonNull(Objects.java:208) at java.base/java.util.AbstractSet.removeAll(AbstractSet.java:167)
No comments:
Post a Comment