当前位置: 首页>>代码示例 >>用法及示例精选 >>正文


Java CopyOnWriteArrayList toArray()用法及代码示例


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



相关用法


注:本文由纯净天空筛选整理自suman_ptnl大神的英文原创作品 CopyOnWriteArrayList toArray() method in Java。非经特殊声明,原始代码版权归原作者所有,本译文未经允许或授权,请勿转载或复制。