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

Java 8ProgrammingObject Oriented Programming

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

Example

 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>();
      arrList.add(50);
      arrList.add(90);
      arrList.add(150);
      arrList.add(200); 
      arrList.add(350); 
      arrList.add(500); 
      arrList.add(650);
      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));
   }
}

Output

CopyOnWriteArrayList String Representation = [50, 90, 150, 200, 350, 500, 650]
Array = [50, 90, 150, 200, 350, 500, 650]
raja
Published on 26-Mar-2019 08:18:10
Advertisements