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<Integer> 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);
        }
    }
}        

The result of the code snippet above:

Number: 10
Number: 20
Number: 30
Number: 40
Number: 50

Wayan

Programmer, runner, recreational diver, live in the island of Bali, Indonesia. Mostly programming in Java, Spring Framework, Hibernate / JPA. Support me by donating.

Leave a Reply