Java Vector - toArray() Method
The java.util.Vector.toArray() method returns an array containing all of the elements in the vector in the correct order; the runtime type of the returned array is that of the specified array. If the given vector fits in the specified array, it is returned therein. Otherwise, a new array is allocated with the runtime type of the specified array and the size of the given vector.
If the vector fits in the specified array with room to spare, the element in the array immediately following the end of the vector is set to null.
Syntax
public <T> T[] toArray(T[] a)
Here, T is the type of element maintained by the container.
Parameters
a |
Specify the array into which the elements of the Vector are to be stored, if it is big enough; otherwise, a new array of the same runtime type is allocated for this purpose. |
Return Value
Returns an array containing all elements of the vector.
Exception
- Throws ArrayStoreException, if the runtime type of a is not a supertype of the runtime type of every element in the vector.
- Throws NullPointerException, if the given array is null.
Example:
In the example below, the java.util.Vector.toArray() method returns an array containing all elements of the given vector.
import java.util.*; public class MyClass { public static void main(String[] args) { //creating a vector Vector<Integer> MyVector = new Vector<Integer>(); //populating vector MyVector.add(50); MyVector.add(20); MyVector.add(30); //creating an empty array Integer[] Arr = new Integer[5]; //convert the vector into an array MyVector.toArray(Arr); //print the array System.out.print("The Arr contains: "); for(int i = 0; i < Arr.length; i++) System.out.print(Arr[i]+ " "); } }
The output of the above code will be:
The Arr contains: 50 20 30 null null
❮ Java.util - Vector