Java Vector copyInto() Method Tutorial

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

What is Java Vector copyInto() Method?

The Java Vector copyInto() method is used to copy the elements of a vector object into an array.

Basically, if we want to create an array out of the elements of a vector object, this method is the way to go with.

Java Vector copyInto() Method Syntax:

public void copyInto(Object[] anArray)

copyInto() Method Parameters:

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

copyInto() Method Return Value:

The return value of this method is void.

copyInto() Method Exceptions:

NullPointerException: We get this exception if the argument of the method is null.

IndexOutOfBoundsException: We get this exception if the target array (the argument of the method) has a size less than the number of elements in the target vector object.

ArrayStoreException: We get this exception if the target array is of incompatible type compared to the datatype of elements in the target vector object.

Example: using Vector copyInto() 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.copyInto(array);

        for (String s: array){
         System.out.println(s);
        }
    }
}

Output:

Jack

Omid

Ellen

John
Facebook
Twitter
Pinterest
LinkedIn

Top Technologies