Java Vector toArray() Example

The toArray() method of java.util.Vector class returns an array containing all of the elements in the vector in proper sequence (from first to last element).

Signature

public Object[] toArray()

This method returns a array of Object which contains all the elements of the vector.

Example

The following example shows the usage of java.util.Vector.toArray() method.

import java.util.Vector;

public class ToArrayMethodVectorExample 
{
    public static void main(String[] args) { 
        // Create Vector vector1 object
        Vector vector1 = new Vector();
        
        //adding elements to vector1
        vector1.add("Element1");
        vector1.add("Element2");
        vector1.add("Element3");
        vector1.add("Element4");
        vector1.add("Element5");
        vector1.add("Element6");
        vector1.add("Element7");
        
        System.out.println("**Contents of vector1**");
        for(String val: vector1)
        {
            System.out.println(val);
        }
        
        // create an array and copy the vector to it
        Object[] array = vector1.toArray();

         // Printing elements of the array
        System.out.println("**Elements of the array**");
        for(Object val : array)
        {
            System.out.println(val.toString());
        }
    }
}

Output

**Contents of vector1**
Element1
Element2
Element3
Element4
Element5
Element6
Element7
**Elements of the array**
Element1
Element2
Element3
Element4
Element5
Element6
Element7

Leave a Reply

Your email address will not be published. Required fields are marked *