📌  相关文章
📜  Java中的 CopyOnWriteArrayList toArray() 方法

📅  最后修改于: 2022-05-13 01:54:33             🧑  作者: Mango

Java中的 CopyOnWriteArrayList toArray() 方法

CopyOnWriteArrayListtoArray()方法用于返回一个数组,该数组包含 CopyOnWriteArrayList 中所有元素的正确顺序。

句法:

public Object[] toArray()
           or
public  T[] toArray(T[] a)

参数:此方法要么不接受参数,要么接受一个数组T[] a作为参数,如果它足够大,该数组就是要存储列表元素的数组;否则,将为此目的分配相同运行时类型的新数组。

返回值:该函数返回一个包含此列表中所有元素的数组

异常:此方法的第一次重载不会引发异常。但是,第二个重载会引发以下异常:

  • ArrayStoreException :如果指定数组的运行时类型不是此列表中每个元素的运行时类型的超类型。
  • 如果指定的数组为 null,则NullPointerException

下面的程序说明了 CopyOnWriteArrayList.toArray() 方法:

方案一:

// 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 ArrLis
            = new CopyOnWriteArrayList();
  
        // 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]

方案二:

// 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 ArrLis
            = new CopyOnWriteArrayList();
  
        // 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() 文档、CopyOnWriteArrayList.toArray(T[]) 文档