Convert Vector to Array in Java Example

This example shows how to convert a Vector object to an Array in Java. This example also shows how to convert Vector to an array using a for loop, toArray method, and Apache Commons library.

How to convert a Vector to an array in Java?

There are several ways using which we can convert a vector object to an array in Java as given below.

1. Using an enhanced for loop

The simplest solution will be to iterate through Vector elements using a for loop and add vector elements to an array one by one.

The below given example shows how to convert a vector of strings to a String array.

Output

2. Using the toArray method

The Vector toArray method returns an array containing all the elements of this vector object in the correct order.

Output

If the array specified in the toArray method is large enough to hold all the elements of the vector object, the same array is filled with the elements and returned. If the specified array is smaller than the vector size, a new array of the same type is created, filled with the vector elements and returned.

It is recommended to pass the array of the same size to the toArray method to avoid the performance penalty of creating a new array.

Important Note: If the array is bigger than the vector size, the array element that comes immediately after the vector elements is set to null to mark the end of the vector elements. However, do not rely on this null value because the vector object itself may contain the null elements.

3. Using the Apache Commons library

If you are using the Apache Commons library in your project, you can use the toPrimitive method of the ArrayUtils class to convert a vector of wrapper objects to an array of equivalent primitive type.

The below given example shows how to convert a Vector of Integer objects to an array of int values.

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

RahimV

RahimV

My name is RahimV and I have over 16 years of experience in designing and developing Java applications. Over the years I have worked with many fortune 500 companies as an eCommerce Architect. My goal is to provide high quality but simple to understand Java tutorials and examples for free. If you like my website, follow me on Facebook and Twitter.

Add Comment

Your email address will not be published. Required fields are marked *