Vector toArray(K[]) in Java

toArray(K[]): This method is available in java.util.Vector class of Java.

Syntax:

<K> K[] java.util.Vector.toArray(K[] a)

This method takes one argument. This method returns an array containing all of the elements in this Vector in the correct order; the runtime type of the returned array is that of the specified array.

Parameters: One parameter is required for this method.

a: the array into which the elements of the Vector are to be stored, if it is big enough; otherwise, a new array of the same runtime type is allocated for this purpose.

Returns: An array containing the elements of the Vector.

Throws:

1. ArrayStoreException - if the runtime type of a, <T>, is not a supertype of the runtime type, <E>, of every element in this Vector.

2. NullPointerException - if the given array is null.

Approach 1: When no exception

Java

import java.util.Arrays;
import java.util.Vector;

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

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

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

        String[] anArray = new String[vector.size()];

        System.out.println(Arrays.toString(
vector.toArray(anArray)));
    }
}

Output:

[Hello, Java, C++, Program]


Approach 2: NullPointerException

Java

import java.util.Arrays;
import java.util.Vector;

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

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

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

        String[] anArray = null;

        System.out.println(Arrays.toString(
vector.toArray(anArray)));
    }
}

Output:

Exception in thread "main" java.lang.NullPointerException: Cannot read the array length because "a" is null at java.base/java.util.Vector.toArray(Vector.java:716)


No comments:

Post a Comment