In this article, we will learn how to convert a Vector to array in Java. Vector class uses dynamic arrays internally, however in certain cases, where we do not require further resizing, we may need to convert it into an Array for better performance.
Java program to convert Vector to array
In the following program, we are using toArray()
method of Vector class, this method returns an array containing all the elements of the vector in the same order.
import java.util.Vector;
public class VectorToArray {
public static void main(String[] args) {
// Creating a Vector of String type
Vector<String> vector = new Vector<String>();
// Adding String elements to the Vector
vector.add("Item1");
vector.add("Item2");
vector.add("Item3");
vector.add("Item4");
vector.add("Item5");
vector.add("Item6");
// Converting Vector to String Array by calling toArray() method
// since vector contains string elements, we are storing the output
// of toArray() method in String array
String[] array = vector.toArray(new String[vector.size()]);
// Displaying Array Elements
System.out.println("String Array Elements :");
for(int i=0; i < array.length ; i++){
System.out.println(array[i]);
}
}
}
Output:
String Array Elements : Item1 Item2 Item3 Item4 Item5 Item6
As we can see the String array contains all the elements of Vector in the same order as they appear in Vector.
Leave a Reply