The toArray() method of Java AbstractCollection class

Java 8Object Oriented ProgrammingProgramming

The toArray() method of the AbstractCollection class is used to return the elements in this collection. The elements are returned in the form of an array.

The syntax is as follows

public Object[] toArray()

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

import java.util.AbstractCollection;

At first, declare AbstractCollection and add some elements

AbstractCollection<Object> absCollection = new ArrayList<Object>();
absCollection.add("Laptop");
absCollection.add("Tablet");
absCollection.add("Mobile");
absCollection.add("E-Book Reader");

Now, use the toArray() method to return the elements in the form of an array

Object[] myArr = absCollection.toArray();

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("Laptop");
      absCollection.add("Tablet");
      absCollection.add("Mobile");
      absCollection.add("E-Book Reader");
      absCollection.add("SSD");
      absCollection.add("HDD");
      System.out.println("AbstractCollection = " + absCollection);
      System.out.println("Count of Elements in the AbstractCollection = " + absCollection.size());
      Object[] myArr = absCollection.toArray();
      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 = [Laptop, Tablet, Mobile, E-Book Reader, SSD, HDD]
Count of Elements in the AbstractCollection = 6
Array returning the elements of this collection =
Laptop
Tablet
Mobile
E-Book Reader
SSD
HDD
raja
Published on 28-Mar-2019 10:23:24
Advertisements