數組是一組由通用名稱引用的 like-typed 變量。 Java 數組可以是兩種類型,即原始數據類型或類的對象(或非原始)引用。對於原始數據類型,實際值存儲在連續的內存位置,而對於類的對象,實際對象存儲在堆段中。
Vector 類實現了一個可增長的對象數組。它與 Java 集合兼容。 Vector 實現了一個動態的 array-means,它可以根據需要增長或縮小。它包含可以使用整數索引(如數組)訪問的組件。
在 Java 中有 3 種方法可以將數組轉換為向量。
- 使用 Collections.addAll 方法
- 使用 Arrays.asList() 方法
- 使用循環
方法一:使用Java Collections addAll()用法及代碼示例方法
用法:
public static boolean addAll(Collection c, T... elements)
參數:此方法將以下參數作為參數
- c-要插入元素的集合
- elements-要插入到 c 中的元素
返回值:如果集合因調用而更改,則此方法返回 true。
例:製作一個數組和一個空向量,在方法中傳遞填充後的數組和空向量,向量將被數組元素填充。
Java
// Java program to Convert Array To Vector
// Using Collections.addAll() method
import java.util.*;
public class array_to_vector {
public static void main(String[] args)
{
String[] arr = { "I", "love", "geeks", "for", "geeks" };
// create a new vector object of the same type
Vector<String> v = new Vector<String>();
// Use the addAll method of the Collections to add
// all array elements to the vector object
Collections.addAll(v, arr);
System.out.println("The vector is");
// printing vector
System.out.println(v);
}
}
輸出
The vector is [I, love, geeks, for, geeks]
方法二:使用Java Arrays asList()用法及代碼示例方法
用法:
public static List asList(T... a)
參數:此方法采用需要轉換為 List 的數組 a。
Example:Vector 構造函數可以采用 List 對象並將其轉換為向量。因此,將數組轉換為 List 並將其傳遞給向量構造函數。
Java
// Java program to Convert Array To Vector
// Using Arrays.asList() method
import java.util.*;
public class array_to_vector {
public static void main(String[] args)
{
String[] arr = { "I", "love", "geeks", "for", "geeks" };
// create a new vector object of the same type
Vector<String> v = new Vector<String>(Arrays.asList(arr));
System.out.println("The vector is");
// printing vector
System.out.println(v);
}
}
輸出
The vector is [I, love, geeks, for, geeks]
方法3:使用循環
例:循環遍曆數組的每個元素,並將該元素一一添加到向量中。
Java
// Java program to Convert Array To Vector
// Using simple iteration method
import java.util.*;
public class array_to_vector {
public static void main(String[] args)
{
String[] arr = { "I", "love", "geeks", "for", "geeks" };
// create a new vector object of the same type
Vector<String> v = new Vector<String>();
for (int i = 0; i < arr.length; i++)
v.addElement(arr[i]);
System.out.println("The vector is");
// printing vector
System.out.println(v);
}
}
輸出
The vector is [I, love, geeks, for, geeks]
相關用法
- Java Vector轉List用法及代碼示例
- Java Vector轉array用法及代碼示例
- Java Vector轉ArrayList用法及代碼示例
- Java ArrayList轉Vector用法及代碼示例
- R DataFrame轉vector用法及代碼示例
- R Named Vector轉DataFrame用法及代碼示例
- R Matrix轉Vector用法及代碼示例
- Java Vector clear()用法及代碼示例
- Java Vector addAll()用法及代碼示例
注:本文由純淨天空篩選整理自apurva__007大神的英文原創作品 Java Program to Convert Array To Vector。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。