Java Vector toArray()
toArray() Java Vector类方法用于获取包含此向量中所有元素的数组以正确的顺序。有两种不同类型的Java toArray()方法,可根据其参数加以区分。这些是:
Java Vector toArray()方法
Java Vector toArray(T [] arr)方法
toArray()方法:
此方法用于返回一个数组,该数组以正确的顺序包含此向量中的所有元素。
toArray(T [] arr)方法:
此方法用于返回以正确顺序包含此向量中所有元素的数组。返回数组的运行时类型是指定数组的运行时类型。
语法
以下是
toArray()方法的声明:
public Object[] toArray()
public <T> T[] toArray(T[] arr)
参数
参数 |
说明 |
必需/可选 |
arr |
如果向量足够大,它是一个数组,向量的元素将存储在该数组中。否则,将为此分配一个具有相同运行时类型的新数组。 |
必需 |
返回
toArray()方法返回包含给定集合中所有元素的数组。
异常
NullPointerException -如果指定的数组为null,则此方法引发异常。
ArrayStoreException -如果arr的运行时类型
<t>
不是此向量中每个元素的运行时类型
的超类型,则此方法引发异常。
兼容性版本
Java 1.2及更高版本
示例1
import java.util.*;
public class VectorToArrayExample1 {
public static void main(String arg[]) {
//Create an empty Vector with an initial capacity of 4
Vector<Integer> vec = new Vector<Integer>(5);
//Create an array with an initial capacity of 4
Integer[] anArray = new Integer[5];
//Add elements in the vector
vec.add(1);
vec.add(2);
vec.add(3);
vec.add(4);
vec.add(5);
//Fill the array from the vector
vec.toArray(anArray);
//Display the contents of an array
System.out.println("Elements are: ");
for (int i = 0; i < anArray.length; i++) {
System.out.println(anArray[i]);
}
}
}
输出:
示例2
import java.util.*;
public class VectorToArrayExample2 {
public static void main(String arg[]) {
//Create Vector "vec" object
Vector<String> vec = new Vector<>();
//Adding elements to vector
vec.add("Java");
vec.add("Android");
vec.add("Python");
vec.add("COBOL");
System.out.println("Contents of a vector are: ");
//Displaying elements of the vector
for(String val: vec)
{
System.out.println(val);
}
//Create an array and copy the vector elements to it
Object[] arr = vec.toArray();
//Displaying elements of the array
System.out.println("Elements of the array: ");
for(Object val : arr)
{
System.out.println(val.toString());
}
}
}
输出:
Contents of a vector are:
Java
Android
Python
COBOL
Elements of the array:
Java
Android
Python
COBOL
示例3
import java.util.*;
public class VectorToArrayExample3 {
public static void main(String arg[]) {
//Creating empty vector object
Vector<Integer> v1 = new Vector<Integer>();
//Creating an array with an intial capacity of 5
Integer[] arr = new Integer[5];
//Adding elemnts to an array
v1.add(10);
v1.add(30);
v1.add(20);
v1.add(40);
//Adding all the elements from v1 to v2 starting at index 1.
v1.toArray(arr);
//Displaying the result
System.out.println("The elements are:");
for(Object obj : arr)
System.out.println(obj);
}
}
输出:
The elements are:
10
30
20
40
null