LinkedHashSet containsAll(Collection) in Java

containsAll(Collection): This method is available in java.util.LinkedHashSet 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.Collection;
import java.util.LinkedHashSet;

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

        LinkedHashSet<String> linkedHashSet =
new LinkedHashSet<>();

        Collection<String> collection =
new LinkedHashSet<String>();
        collection.add("Java");
        collection.add("C++");
        linkedHashSet.add("Hello");

        System.out.println(linkedHashSet.containsAll(
collection));

    }
}

Output:

false


Approach 2: NullPointerException

Java

import java.util.Collection;
import java.util.LinkedHashSet;

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

        LinkedHashSet<String> linkedHashSet =
new LinkedHashSet<>();

        Collection<String> collection = null;
        linkedHashSet.add("Hello");

        System.out.println(linkedHashSet.containsAll(
collection));

    }
}

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