HashSet containsAll(Collection) in Java

containsAll(Collection): This method is available in java.util.HashSet class of Java.

Syntax:

boolean java.util.AbstractCollection.containsAll(Collection<?> c)

This method takes one argument. This method returns true if this collection contains all of the elements in the specified collection.

Parameters: One parameter is required for this method.

c: collection to be checked for containment in this collection.

Returns: true if this collection contains all of the elements in the specified collection.

Throws:

1. ClassCastException - if the types of one or more elements in the specified collection are incompatible with this collection.

2. NullPointerException - if the specified collection contains one or more null elements and this collection does not permit null elements, or if the specified collection is null.

Approach 1: When no exception

Java

import java.util.HashSet;

public class HashSetcontainsAll {
    public static void main(String[] args) {

        HashSet<String> hashSet = new HashSet<String>();

        hashSet.add("Hello");
        hashSet.add("Java");
        hashSet.add("C++");
        hashSet.add("Hello");

        HashSet<String> hashSet2 = new HashSet<String>();

        hashSet.add("Hello");
        hashSet.add("Java");
        hashSet.add("C++");
        hashSet.add("Hello");

        System.out.println(hashSet.containsAll(hashSet2));

    }
}

Output:

true


Approach 2: NullPointerException 

Java

import java.util.HashSet;

public class HashSetcontainsAll {
    public static void main(String[] args) {

        HashSet<String> hashSet = new HashSet<String>();

        hashSet.add("Hello");
        hashSet.add("Java");
        hashSet.add("C++");
        hashSet.add("Hello");

        HashSet<String> hashSet2 = null;

        System.out.println(hashSet.containsAll(hashSet2));

    }
}

Output:

Exception in thread "main" java.lang.NullPointerException: Cannot invoke "java.util.Collection.iterator()" because "c" is null at java.base/java.util.AbstractCollection.containsAll(AbstractCollection.java:308)


No comments:

Post a Comment