Java - Convert a Vector to an Array of Strings
In this tutorial, we'll see how to convert a Vector to an array of Strings in java. There are two methods we can use to get an array of String from Vector.Vector to Array with using toArray()
Let's take a look at the example below where we are converting a Vector of Strings to an array using the method toArray().public String toArray(): returns an array of strings.
import java.util.Vector;Runtime:
public class VectorToArray {
public static void main(String[] args) {
Vector< String> vector = new Vector< String> ();
//add elements
vector.add("elt1");
vector.add("elt2");
vector.add("elt3");
System.out.println("Vector Elements:");
for(String e:vector)
System.out.println(e);
//Convert Vector to an array
String[] array = vector.toArray(new String[vector.size()]);
//display elements
System.out.println("Elements de array:");
for(String e:array){
System.out.println(e);
}
}
}
Vector Elements:Note that it is more efficient to pass the correctly array size new String[vector.size()] in the method because, in this case, the method will use this array.
elt1
elt2
elt3
Array Elements:
elt1
elt2
elt3
Vector to Array using copyInto()
This method consists of proceeding in two steps:
- Create an array with an initialized size with that of Vector
- Call the copyInto(String array[]) method on Vector
The copyInto() allows you to copy all the elements of the Vector collection to a new array.
import java.util.Vector;
public class VectorToArray {
public static void main(String[] args) {
Vector< String> vector = new Vector< String> ();
//add elements
vector.add("s1");
vector.add("s2");
vector.add("s3");
System.out.println("Vector Elements:");
for(String e:vector)
System.out.println(e);
//Convert Vector to an array
String[] array = new String[vector.size()];
vector.copyInto(array);
//display elements
System.out.println("Elements copied to array:");
for(String e:array){
System.out.println(e);
}
}
}
Runtime:
Vector Elements:
s1
s2
s3
Elements copied to array:
s1
s2
s3