Convert a Vector to an Array in Java



A Vector can be converted into an Array using the java.util.Vector.toArray() method. This method requires no parameters and it returns an Array that contains all the elements of the Vector in the correct order.

A program that demonstrates this is given as follows −

Example

 Live Demo

import java.util.Vector;
public class Demo {
   public static void main(String args[]) {
      Vector vec = new Vector();
      vec.add(7);
      vec.add(3);
      vec.add(5);
      vec.add(2);
      vec.add(8);
      Object[] arr = vec.toArray();
      System.out.println("The Array elements are: ");
      for (int i = 0; i < arr.length; i++) {
         System.out.println(arr[i]);
      }
   }
}

The output of the above program is as follows −

The Array elements are:
7
3
5
2
8

Now let us understand the above program.

The Vector is created. Then Vector.add() is used to add the elements to the Vector. The method Vector.toArray() is used to convert the Vector into an Array. Then the Array elements are displayed using a for loop. A code snippet which demonstrates this is as follows −

Vector vec = new Vector();
vec.add(7);
vec.add(3);
vec.add(5);
vec.add(2);
vec.add(8);
Object[] arr = vec.toArray();
System.out.println("The Array elements are: ");
for (int i = 0; i < arr.length; i++) {
   System.out.println(arr[i]);
}
Updated on: 2020-06-30T08:18:22+05:30

1K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements