Convert a Vector to an array in Java

Java 8Object Oriented ProgrammingProgramming

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]);
}
raja
Published on 07-Feb-2019 16:48:51
Advertisements