Java program to convert vector to array

Given a Vector in Java, the task is to convert this Vector to Array.

Examples:

Input: Vector: ['G', 'e', 'e', 'k', 's'] 
Output: Array: ['G', 'e', 'e', 'k', 's'] 

Input: Vector: [1, 2, 3, 4, 5]
Output: Array: [1, 2, 3, 4, 5] 

Method 1:

Approach:

  1. Get the Vector.
  2. Convert the Vector to Object array using toArray() method.
  3. Convert the thing array to desired type array using Arrays.copyOf() method.
  4. Return the print the Array

Below is the implementation of the above approach:

// Java program to convert
// Vector to Array

import java.util.*;

public class GFG {

	// Function to convert Vector to Array
	public static  Object[] convertVectorToArray(Vector vector)
	{

		// Converting Vector to Array
		Object[] array = vector.toArray();

		return array;
	}

	public static void main(String args[])
	{
		// Creating linked list
		Vector
			vector = new Vector();

		// Adding elements to the linked list
		vector.add("G");
		vector.add("e");
		vector.add("e");
		vector.add("k");
		vector.add("s");

		// Print the Vector
		System.out.println("Vector: "
						+ vector);

		// Converting Vector to Object Array
		Object[] objArray = convertVectorToArray(vector);

		// Convert Object[] to String[]
		String[] array = Arrays.copyOf(objArray,
									objArray.length,
									String[].class);
		// Print the String Array
		System.out.println("Array: "+ Arrays.toString(array));
	}
}

Output:

Vector: [G, e, e, k, s]
Array: [G, e, e, k, s]

Method 2:

Approach

  1. Created a Vector String type.
  2. Added elements into Vector using add(E) method.
  3. Converted the Vector to Array using toArray(new String[vector.size()]).

Below is that the implementation of the above approach:

// Java program to convert
// Vector to Array

import java.util.*;

public class GFG {

	public static void main(String args[])
	{
		// Creating linked list
		Vector
			vector = new Vector();

		// Adding elements to the linked list
		vector.add("G");
		vector.add("e");
		vector.add("e");
		vector.add("k");
		vector.add("s");

		// Print the Vector
		System.out.println("Vector: "+ vector);

		//Converting Vector to String Array
				String[] array = vector.toArray(new String[vector.size()]);

		// Print the String Array
		System.out.println("Array: "+ Arrays.toString(array));
	}
}

 

Submit Your Programming Assignment Details