Vector containsAll(Collection) in Java

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

Syntax:

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

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

Parameters: One parameter is required for this method.

c: a collection whose elements will be tested for containment in this Vector.

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

Throws:

NullPointerException - if the specified collection  is null

Approach 1: When no exception

Java

import java.util.Collection;
import java.util.Vector;

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

        Vector<String> vector = new Vector<>();

        vector.add("Hello");
        vector.add("Java");
        vector.add("C++");
        vector.add("Program");

        Collection<String> c = new Vector<>();

        vector.add("Hello");
        vector.add("Java");
        vector.add("C++");
        vector.add("Program");

        System.out.println(vector.containsAll(c));
    }
}

Output:

true


Approach 2: NullPointerException

Java

import java.util.Collection;
import java.util.Vector;

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

        Vector<String> vector = new Vector<>();

        vector.add("Hello");
        vector.add("Java");
        vector.add("C++");
        vector.add("Program");

        Collection<String> c = null;

        System.out.println(vector.containsAll(c));
    }
}

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) at java.base/java.util.Vector.containsAll(Vector.java:879)


No comments:

Post a Comment