CopyOnWriteArrayList的toArray()方法用於按正確順序返回包含CopyOnWriteArrayList中所有元素的數組。
用法:
public Object[] toArray() or public <T> T[] toArray(T[] a)
參數:該方法或者不接受任何參數,或者將數組T [] a作為參數,如果足夠大,該數組就是要存儲列表元素的數組。否則,將為此分配一個具有相同運行時類型的新數組。
返回值:該函數返回一個包含此列表中所有元素的數組。
異常:此方法的第一次重載不會引發任何異常。但是,第二次重載引發以下異常:
- ArrayStoreException:如果指定數組的運行時類型不是此列表中每個元素的運行時類型的超類型。
- NullPointerException 如果指定的數組為null
以下示例程序旨在說明CopyOnWriteArrayList.toArray()方法:
程序1:
// Java Program to illustrate the
// CopyOnWriteArrayList toArray() method in Java
import java.util.concurrent.CopyOnWriteArrayList;
import java.util.*;
public class GFG {
public static void main(String[] args)
{
// create object of CopyOnWriteArrayList
CopyOnWriteArrayList<Integer> ArrLis
= new CopyOnWriteArrayList<Integer>();
// Add elements
ArrLis.add(32);
ArrLis.add(67);
ArrLis.add(98);
ArrLis.add(100);
// print CopyOnWriteArrayList
System.out.println("CopyOnWriteArrayList: "
+ ArrLis);
// Get the array of the elements
// of the CopyOnWriteArrayList
// using toArray() method
Object[] arr = ArrLis.toArray();
System.out.println("Elements of CopyOnWriteArrayList"
+ " as Array: "
+ Arrays.toString(arr));
}
}
輸出:
CopyOnWriteArrayList: [32, 67, 98, 100] Elements of CopyOnWriteArrayList as Array: [32, 67, 98, 100]
程序2:
// Java Program to illustrate the
// CopyOnWriteArrayList toArray(T[]) method in Java
import java.util.concurrent.CopyOnWriteArrayList;
import java.util.*;
public class GFG {
public static void main(String[] args)
{
// create object of CopyOnWriteArrayList
CopyOnWriteArrayList<Integer> ArrLis
= new CopyOnWriteArrayList<Integer>();
// Add elements
ArrLis.add(32);
ArrLis.add(67);
ArrLis.add(98);
ArrLis.add(100);
// print CopyOnWriteArrayList
System.out.println("CopyOnWriteArrayList: "
+ ArrLis);
// Get the array of the elements
// of the CopyOnWriteArrayList
// using toArray(T[]) method
Integer arr[] = new Integer[ArrLis.size()];
arr = ArrLis.toArray(arr);
System.out.println("Elements of CopyOnWriteArrayList"
+ " as Array: "
+ Arrays.toString(arr));
}
}
輸出:
CopyOnWriteArrayList: [32, 67, 98, 100] Elements of CopyOnWriteArrayList as Array: [32, 67, 98, 100]
參考: CopyOnWriteArrayList.toArray() doc,CopyOnWriteArrayList.toArray(T [])doc
相關用法
- Java CopyOnWriteArrayList contains()用法及代碼示例
- Java CopyOnWriteArrayList add()用法及代碼示例
- Java CopyOnWriteArrayList get()用法及代碼示例
- Java CopyOnWriteArrayList containsAll()用法及代碼示例
- Java CopyOnWriteArrayList isEmpty()用法及代碼示例
- Java CopyOnWriteArrayList lastIndexOf()用法及代碼示例
- Java CopyOnWriteArrayList spliterator()用法及代碼示例
- Java CopyOnWriteArrayList toString()用法及代碼示例
- Java CopyOnWriteArrayList size()用法及代碼示例
- Java CopyOnWriteArrayList listIterator()用法及代碼示例
- Java CopyOnWriteArrayList iterator()用法及代碼示例
- Java CopyOnWriteArrayList indexOf()用法及代碼示例
- Java CopyOnWriteArrayList addIfAbsent()用法及代碼示例
- Java CopyOnWriteArrayList clear()用法及代碼示例
- Java CopyOnWriteArrayList clone()用法及代碼示例
注:本文由純淨天空篩選整理自suman_ptnl大神的英文原創作品 CopyOnWriteArrayList toArray() method in Java。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。