The toArray(T[] a) T method of Java AbstractCollection class

Java 8Object Oriented ProgrammingProgramming

The difference between toArray() and toArray(T[] arr) in Java AbstractCollection 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, arr is the array into which the elements of this collection are to be stored.

To work with AbstractCollection class in Java, import the following package

import java.util.AbstractCollection;

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

Example

 Live Demo

import java.util.ArrayList;
import java.util.AbstractCollection;
public class Demo {
   public static void main(String[] args) {
      AbstractCollection<Object> absCollection = new ArrayList<Object>();
      absCollection.add("HDD");
      absCollection.add("Earphone");
      absCollection.add("Headphone");
      absCollection.add("Card Reader");
      absCollection.add("SSD");
      absCollection.add("Pen Drive");
      System.out.println("AbstractCollection = " + absCollection);
      System.out.println("Count of Elements in the AbstractCollection = " + absCollection.size());
      String[] myArr = new String[5];
      myArr = absCollection.toArray(myArr);
      System.out.println("Array returning the elements of this collection = ");
      for (int i = 0; i < myArr.length; i++)
      System.out.println(myArr[i]);
   }
}

Output

AbstractCollection = [HDD, Earphone, Headphone, Card Reader, SSD, Pen Drive]
Count of Elements in the AbstractCollection = 6
Array returning the elements of this collection =
HDD
Earphone
Headphone
Card Reader
SSD
Pen Drive
raja
Published on 28-Mar-2019 11:37:47
Advertisements