How do I convert a Vector into an array?

This example demonstrates how to convert a Vector object into an array. You can use the Vector.copyInto(Object[] array) method to create a copy of the Vector object in array form.

package org.kodejava.example.util;

import java.util.Vector;

public class VectorToArray {
    public static void main(String[] args) {
        Vector vector = new Vector();
        vector.add(10);
        vector.add(20);
        vector.add(30);
        vector.add(40);
        vector.add(50);

        // 
        // Declares and initializes an Integer array.
        //
        Integer[] numbers = new Integer[vector.size()];

        // 
        // Copies the components of this vector into the specified 
        // array of Integer
        //
        vector.copyInto(numbers);

        for (Integer number : numbers) {
            System.out.println("number: " + number);
        }
    }
}

Wayan Saryada

Programmer, runner, recreational diver, currently living in the island of Bali, Indonesia. Mostly programming in Java, creating web based application with Spring Framework, Hibernate / JPA.

Leave a Reply