java toarray
向量类toArray()方法 (Vector Class toArray() method)
Syntax:
句法:
public Object[] toArray();
public Object[] toArray(Type[] ty);
toArray() method is available in java.util package.
toArray()方法在java.util包中可用。
toArray() method is used to return an array of elements that exists in this Vector.
toArray()方法用于返回此Vector中存在的元素的数组。
toArray(Type[] ty) method is used to return an array that holds all the existing elements in this vector.
toArray(Type [] ty)方法用于返回一个数组,该数组包含此向量中的所有现有元素。
These methods may throw an exception at the time of representing an array.
这些方法在表示数组时可能会引发异常。
- ArrayStoreException: This exception may throw when the given parameter is not in a range.ArrayStoreException :如果给定参数不在范围内,则可能引发此异常。
- NullPointerException: This exception may throw when the given parameter is null exists.NullPointerException :当给定参数为null时,可能引发此异常。
These are non-static methods and it is accessible with class objects and if we try to access these methods with the class name then we will get an error.
这些是非静态方法,可通过类对象访问,如果尝试使用类名访问这些方法,则会收到错误消息。
Parameter(s):
参数:
In the first case, toArray()
在第一种情况下, toArray()
- It does not accept any parameters.
In the first case, toArray(Type[] ty)
在第一种情况下, toArray(Type [] ty)
- Type[] ty – represents the array where we have to store all existing elements of this Vector.
- Type [] ty –表示我们必须存储此Vector所有现有元素的数组。
Return value:
返回值:
In the first case, the return type of the method is Object [] – It returns an object array (Object []) that hold all elements exists in this vector.
在第一种情况下,该方法的返回类型为Object [] –它返回一个对象数组(Object []),该数组保存此向量中存在的所有元素。
In the second case, the return type of the method is Type [] – It returns an array of same type that holds vector elements.
在第二种情况下,该方法的返回类型为Type [] –它返回一个包含向量元素的相同类型的数组。
Example:
例:
// Java program to demonstrate the example
// of toArray() method of Vector
import java.util.*;
public class ToArrayOfVector {
public static void main(String[] args) {
// Instantiates a vector object
String[] s = {};
Vector < String > v = new Vector < String > (Arrays.asList(s));
String[] str = new String[5];
// By using add() method is to add
// the elements in vector
v.add("C");
v.add("C++");
v.add("SFDC");
v.add("JAVA");
//Display Vector
System.out.println("v: " + v);
// By using toArray() method is to
// return an array that contains all the
// vector elements
str = v.toArray(str);
System.out.println("v.toArray(): ");
for (int i = 0; i < str.length; ++i)
System.out.println(str[i]);
// By using toArray(array) method is to
// return an array that contains all the
// vector elements by using an array
v.toArray(str);
System.out.println("v.toArray(str): ");
for (int i = 0; i < str.length; ++i)
System.out.println(str[i]);
}
}
Output
输出量
v: [C, C++, SFDC, JAVA]
v.toArray():
C
C++
SFDC
JAVA
null
v.toArray(str):
C
C++
SFDC
JAVA
null
翻译自: https://www.includehelp.com/java/vector-toarray-method-with-example.aspx
java toarray