The toArray(T[] a) method of CopyOnWriteArrayList in Java

The difference between toArray() and toArray(T[] arr) of the CopyOnWriteArrayList class is that both the methods returns an array containing all of the elements in this collection, but the latter has some additional features i.e. the runtime type of the returned array is that of the specified array.

The syntax is as follows

public <T> T[] toArray(T[] arr)

Here, the parameter arr is the array into which the elements of the list are to be stored.

To work with CopyOnWriteArrayList class, you need to import the following package

import java.util.concurrent.CopyOnWriteArrayList;

The following is an example to implement CopyOnWriteArrayList class toArray() method in Java


 Live Demo

import java.util.Arrays; import java.util.concurrent.CopyOnWriteArrayList;
public class Demo {
   public static void main(String[] args) {
      CopyOnWriteArrayList<Integer> arrList = new CopyOnWriteArrayList<Integer>();
      System.out.println("CopyOnWriteArrayList String Representation = " + arrList.toString());
      Integer[] myArr = new Integer[arrList.size()];
      myArr = arrList.toArray(myArr);
      System.out.println("Array = "+Arrays.toString(myArr));


CopyOnWriteArrayList String Representation = [50, 90, 150, 200, 350, 500, 650]
Array = [50, 90, 150, 200, 350, 500, 650]