Vector removeAll(Collection) in Java

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

Syntax:

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

This method takes one argument. This method removes from this Vector all of its elements that are contained in the specified Collection.

Parameters: One parameter is required for this method.

c: a collection of elements to be removed from the 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 VectorremoveAll {
    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.removeAll(c));
    }
}

Output:

true


Approach 2: NullPointerException

Java

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

public class VectorremoveAll {
    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.removeAll(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.removeAll(Vector.java:930)


No comments:

Post a Comment