How to Convert Vector to Array in Java? 2 Examples

In the last article, we have learned how to convert a LinkedList to array in Java and in today's tutorial you will learn how to convert a Vector to array in Java. There is a similarity between Vector and LinkedList, both implements the List interface. Even though Vector is a legacy class and exists in Java from JDK 1.1 long before Java Collection framework was introduced, it was later retrofitted to implement the List interface. You can use the same toArray() method to convert a Vector to an array in Java. Similar to LinkedList, you can convert Vector of any object to an array of the corresponding object, the only restriction is that you cannot convert a vector of Integers to an array of ints or Vector of Float objects to an array of floats, which applies to our linked list solution as well.

For a Java developer, a good knowledge of different Collection classes are very important because that will enable you to chose the right Collection class for the job. For example, if you know that Vector implements List interface then you know that it is an ordered collection and when you convert Vector to array the order of elements will remain same i.e. the order on which they are inserted.

You can learn Java collection framework by starting with a book like Core Java for Impatient, this will give you a basic idea of each collection class e.g. the data structure they are based upon, important features and what makes different from others. Once you know the basics you can go for an expert book like Java Generics and Collection.

The time invested in learning all important classes of Collection framework e.g. Vector, ArrayList, HashMap, ConcurrentHashMap is definitely worth and will help on both interview and your job.

Java Program to convert Vector to array in Java

Here is our sample program to convert a Vector to an array in Java without using any third party library like Apache Commons or Guava. Similar to the earlier tutorial, this article also has two examples, first one converts a Vector of String to an array of String and the second one converts Vector of Integer values to an array of Integer objects.

While converting Vector to array just be mindful of one key difference between a Vector and an array that an array can hold both primitive and reference types but Vector can only hold reference types, which means you can have array of ints but you cannot have Vector of ints, instead, wrapper object Integer is used in place of int primitive.

This means when you convert a Vector of Integer, you will get an array of Integer, not the array of int primitives. To learn more about the difference between primitive and reference variables, see this article.

Here is step by step guide to convert a Vector to array in Java:

How to convert Vector to array in Java

and here is our Java program based upon these steps:

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

public class VectorToArray{

public static void main(String args[]){

// creating and initializing a Vector of String
Vector<String> vectorOfBrands = new Vector<>();

// printing the contents of Vector before conversion
System.out.println("Vector: " + vectorOfBrands);

// Converting the Vector to array
String[] arrayOfBooks = vectorOfBrands.toArray(new String[vectorOfBrands.size()]);

// printing contents of array after conversion
System.out.println("String array: " + Arrays.toString(arrayOfBooks));

// Second example - Creating Vector of Integers
Vector<Integer> vectorOfAges = new Vector<>();

// printing Vector
System.out.println("Vector: " + vectorOfAges);

// converting Vector of Integer to array of integers
// int[] score = vectorOfScores.toArray(new int[vectorOfScores.size()]); // compile time error
Integer[] scores = vectorOfAges.toArray(new Integer[vectorOfAges.size()]); // this is ok

// printing array
System.out.println("Integer array: " + Arrays.toString(scores));

Vector: [Google, Apple, Microsoft]
String array: [Google, Apple, Microsoft]
Vector: [21, 32, 43]
Integer array: [21, 32, 43]

You can see in both the cases we have successfully converted a Vector of String and Integer to an array of String and Integer. The order of the element is preserved because Vector implements the List interface, which guarantees insertion order i.e. the order on which elements are inserted.

While converting Vector of Integer object to array, As I said, you need to pass the toArray() method an array of Integer and not the array of int primitive i.e. int[]While converting Vector of Integer object to array, As I said, you need to pass the toArray() method an array of Integer and not the array of int primitive i.e. int[] will not work. It will give compile time error.

That's all about how to convert a Vector to an array in Java. Just remember that toArray() method accepts an array of specified type. If you provide an array which is smaller than linked list than this method can also create a new array and in case array is bigger than linked list than it will put nulls on remaining slots. It also maintains the original order of elements in linked list while converting to an array.

Further Learning
Java In-Depth: Become a Complete Java Engineer
Java Fundamentals: Collections
Data Structures and Algorithms: Deep Dive Using Java

No comments:

Post a Comment

Feel free to comment, ask questions if you have any doubt.