Vector addAll(Collection) in Java

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

Syntax:

boolean java.util.Vector.addAll(Collection<? extends K> c)

This method takes one argument. This method appends all of the elements in the specified Collection to the end of this Vector, in the order that they are returned by the specified Collection's Iterator.

Parameters: One parameter is required for this method.

c: elements to be inserted into this Vector.

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

Throws:

NullPointerException - if the specified collection is null.

Approach 1: When no exception

Java

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

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

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

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

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

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

Output:

true


Approach 2: NullPointerException

Java

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

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

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

        Collection<String> c = null;
        System.out.println(vector.addAll(c));
    }
}

Output:

Exception in thread "main" java.lang.NullPointerException: Cannot invoke "java.util.Collection.toArray()" because "c" is null at java.base/java.util.Vector.addAll(Vector.java:896)


No comments:

Post a Comment