Did this blog help you solve a problem? Tip me with Bitcoins at: 17dQktcAmU4urXz7tGk2sbuiCqykm3WLs6

Saturday, July 10, 2010

Convert an Array into a Vector in Java

To convert an Array into a java.util.Vector we can use the java.util.Arrays class's asList method. The following code example demonstrates converting an Array of Strings to a Vector of Strings.

import java.util.Arrays;
import java.util.Iterator;
import java.util.Vector;

/**
* Java 1.4+ Compatible
* The following example code demonstrates converting an Array of Strings to a Vector of Strings
*/
public class Array2Vector {

public static void main(String[] args) {

// initialize array with some data
String[] sa = new String[] { "A", "B", "C" };
// convert array to Vector
Vector v = new Vector(Arrays.asList(sa));

// iterate over each element in Vector
Iterator iterator = v.iterator();
while (iterator.hasNext()) {
// Print element to console
System.out.println((String) iterator.next());
}
}
}



Here is the output of the example code:
A
B
C

No comments: