Skip to content

Convert Array to Vector in Java Example

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.

We can use this method to add all array elements to the vector object as given below.

Output

2. Using the asList method of the Arrays class

The Vector class provides a constructor that accepts a collection object.

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.

Output

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.

Output

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

About the author

Leave a Reply

Your email address will not be published.