How to Convert Vector to Array in Java?
Last Updated :
15 Nov, 2021
As we all know an array is a group of liked-typed variables that are referred to by a common name while on the other hand vectors basically fall in legacy classes but now it is fully compatible with collections. It is found in java.util package and implement the List interface which gives a superior advantage of using all the methods of List interface here. Now the problem simply breaks down to how to use these methods defined in order for the conversion of vector to array for which we will be proposing ways as listed below as follows:
Methods:
- Using toArray() method of Vector class
- Using toArray(new String[vector.size()]) method
Let us go through an illustration before landing upon methods to get the understanding of approaches real quick.
Illustrations:
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: Using toArray() method of Vector class
Approach:
- Get the Vector.
- Convert the Vector to Object array using toArray() method
- Convert the Object array to desired type array using Arrays.copyOf() method
- Return the print the Array.
Example:
Java
import java.util.*;
public class GFG {
public static <T>
Object[] convertVectorToArray(Vector<T> vector)
{
Object[] array = vector.toArray();
return array;
}
public static void main(String args[])
{
Vector<String> vector = new Vector<String>();
vector.add( "G" );
vector.add( "e" );
vector.add( "e" );
vector.add( "k" );
vector.add( "s" );
System.out.println( "Vector: " + vector);
Object[] objArray = convertVectorToArray(vector);
String[] array = Arrays.copyOf(
objArray, objArray.length, String[]. class );
System.out.println( "Array: "
+ Arrays.toString(array));
}
}
|
Output:
Vector: [G, e, e, k, s]
Array: [G, e, e, k, s]
Method 2: Using toArray(new String[vector.size()]) method
Approach:
- Created a Vector String type.
- Added elements into Vector using add(E) method.
- Converted the Vector to Array using toArray(new String[vector.size()]).
Example:
Java
import java.util.*;
public class GFG {
public static void main(String args[])
{
Vector<String> vector = new Vector<String>();
vector.add( "G" );
vector.add( "e" );
vector.add( "e" );
vector.add( "k" );
vector.add( "s" );
System.out.println( "Vector: " + vector);
String[] array
= vector.toArray( new String[vector.size()]);
System.out.println( "Array: "
+ Arrays.toString(array));
}
}
|
Output:
Vector: [G, e, e, k, s]
Array: [G, e, e, k, s]
Share your thoughts in the comments
Please Login to comment...