Java Vector toArray() Method Tutorial

In this section, we will learn what the Vector toArray() method is and how to use it in Java.

What is Java Vector toArray() Method?

The Java Vector toArray() method is used to get the elements of a vector object and store them in an array.

Basically, this method is a way of creating an array representation of elements in the target vector object.

Note: the elements in the array is a copy of the elements in the target vector object. This means changing the values in the array for example, won’t affect the target vector.

Java Vector toArray() Method Syntax:

public <T> T[] toArray(T[] a)

toArray() Method Parameters:

The method takes one argument and that is a reference to an array that we want to copy the elements of the target vector object there.

toArray() Method Return Value:

The return value of this method is a reference to the reference array that we’ve passed as the argument to the method.

toArray() Method Exceptions:

The method might throw two exceptions:

ArrayStoreException: We get this exception of the type of the argument array is not the same as the elements of the target vector. Basically, if the datatype was incompatible, this exception will be thrown.

NullPointerException: We get this exception if the argument we set for this method is in fact a null value.

Example: using Vector toArray() method

import java.util.Vector; 
public class Main {

    public static void main(String[] args){
        
        Vector <String> vector = new Vector<>();
        vector.add("Jack");
        vector.add("Omid");
        vector.add("Ellen");
        vector.add("John");

        String array[] = new String[vector.size()];
        vector.toArray(array);
        
        for (String s: array){
         System.out.println(s);
        }
    }
}

Output:

Jack

Omid

Ellen

John

Leave a Reply