<T> T[ ] toArray(T[ ] a)
描述 (Description)
toArray(T[] a)方法用于以正确的顺序返回包含此Vector中所有元素的数组。
声明 (Declaration)
以下是java.util.Vector.toArray()方法的声明
public <T> T[] toArray(T[] a)
参数 (Parameters)
a - 这是要存储Vector元素的数组,如果它足够大的话; 否则,为此目的分配相同运行时类型的新数组。
返回值 (Return Value)
方法调用返回一个包含Vector元素的数组。
异常 (Exception)
ArrayStoreException - 如果a的运行时类型不是此Vector中每个元素的运行时类型的超类型,则抛出此异常。
NullPointerException - 如果给定数组为null,则抛出此异常。
例子 (Example)
以下示例显示了java.util.Vector.toArray()方法的用法。
package com.iowiki;
import java.util.*;
import java.util.Arrays;
public class VectorDemo {
public static void main(String[] args) {
// create an empty Vector vec with an initial capacity of 4
Vector<Integer> vec = new Vector<Integer>(4);
// create an array
Integer[] anArray = new Integer[4];
// use add() method to add elements in the vector
vec.add(4);
vec.add(3);
vec.add(2);
vec.add(1);
// fill the array from the vector
vec.toArray(anArray);
// check the content of the array
System.out.println("Elements are: ");
for (int i = 0; i < anArray.length; i++) {
System.out.println(anArray[i]);
}
}
}
让我们编译并运行上面的程序,这将产生以下结果。
Elements are:
4
3
2
1