Couple of weeks back we shared a tutorial on ArrayList to String Array conversion. In this tutorial, we are gonna see how to convert a Vector to String Array in Java.
Example
Lets have a look at the below example where we are converting a Vector of Strings to an array. We are using toString() method of Vector class to do this.
public String toString()
: It returns a string representation of this Vector, containing the String representation of each element.
import java.util.Vector; public class VectorToArray { public static void main(String[] args) { // Creating a Vector of String elements Vector<String> vector = new Vector<String>(); // Add elements to Vector vector.add("Item1"); vector.add("Item2"); vector.add("Item3"); vector.add("Item4"); vector.add("Item5"); vector.add("Item6"); //Converting Vector to 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
The steps we followed in above code are:
1) Created a Vector of type String
2) Added elements to it using add(Element E) method of Vector class.
3) Converted the Vector to Array using toArray(new String[vector.size()])
.
Leave a Reply