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:
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
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)); } }