Vector retainAll(Collection) in Java

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

Syntax:

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

This method takes one argument. This method retains only the elements in this Vector that are contained in the specified Collection.

Parameters: One parameter is required for this method.

c: a collection of elements to be retained in this Vector.

Returns: true if this Vector changed as a result of the call.

Throws:

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

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

Approach 1: When no exception

Java

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

public class VectorretainAll {
    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<>();

        c.add("Hello");
        c.add("Java");

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

Output:

true


Approach 2: NullPointerException 

Java

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

public class VectorretainAll {
    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.retainAll(c));
    }
}

Output:

Exception in thread "main" java.lang.NullPointerException at java.base/java.util.Objects.requireNonNull(Objects.java:208) at java.base/java.util.Vector.retainAll(Vector.java:954)


No comments:

Post a Comment