This example shows how to convert an array to a Vector object in Java. This example also shows how to convert an array to a vector object using the asList method, addAll method, and Apache Common library.
How to convert an array to a Vector object in Java?
There are several ways using which we can convert an array to a vector object in Java as given below.
1. Using the addAll method of the Collections class
The Collections addAll
method adds all the specified elements to the specified collection object.
1 |
public static <T> boolean addAll(Collection<? super T> c, T... elements) |
We can use this method to add all array elements to the vector object as given below.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 |
import java.util.Collections; import java.util.Vector; public class ConvertArrayToVector { public static void main(String[] args) { String[] strColors = {"white", "orange", "black"}; //create new vector object of the same type Vector<String> vColors = new Vector<String>(); /* * Use the addAll method of the Collections to add * all array elements to the vector object */ Collections.addAll(vColors, strColors); System.out.println("Vector contains: " + vColors); } } |
Output
1 |
Vector contains: [white, orange, black] |
2. Using the asList method of the Arrays class
The Vector class provides a constructor that accepts a collection object.
1 |
public Vector(Collection<? extends E> collection) |
This constructor creates a new vector object containing all the elements of the specified collection object. We will convert the array to a List object first to utilize this constructor using the asList
method of the Arrays class.
The below given example shows how to convert a String array to a vector object using this approach.
1 2 3 4 5 6 7 8 9 |
String[] strColors = {"white", "orange", "black"}; //convert array to list List<String> list = Arrays.asList(strColors); //create new vector from the list elements Vector<String> vColors = new Vector<String>( list ); System.out.println("Vector contains: " + vColors); |
Output
1 |
Vector contains: [white, orange, black] |
3. Using the Apache Commons library
If you are using the Apache Commons library, you can use the addAll
method of the CollectionUtils class to add array elements to a vector object as given below.
1 2 3 4 5 6 7 8 9 10 11 12 |
String[] strColors = {"white", "orange", "black"}; //create new vector object of the same type Vector<String> vColors = new Vector<String>(); /* * Use the addAll method of the CollectionUtils class to add * all array elements to the vector object */ CollectionUtils.addAll(vColors, strColors); System.out.println("Vector contains: " + vColors); |
Output
1 |
Vector contains: [white, orange, black] |
This example is a part of the Java Vector Tutorial with Examples.
Please let me know your views in the comments section below.
References:
Java 8 Vector Documentation