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