Collection to Array Java

You have seen earlier how to convert an array into collection class. Now let us see the other way of converting collection to array with toArray() method.

Method signature of toArray() method as defined in java.util.Collection interface.

  • T[] toArray(T[] a): Returns an array with the elements of the collection.
Following example on collection to array converts ArrayList elements to array.
import java.util.*;
public class CollectionToArray
  public static void main(String args[])
  {                                   // create ArrayList object and add some elements
    ArrayList al1 = new ArrayList();         
    al1.add("Hello"); al1.add(10.54); al1.add(123); al1.add(new Date());

    System.out.println("ArrayList elements: " + al1);

    Object objArray[] =  al1.toArray();

    System.out.println("\nArray elements: " + Arrays.toString(objArray));

Collection to Array JavaOutput Screenshot on Collection to Array Java

A collection ArrayList object al1 is created and added with elements. The toArray() method returns an object array with the elements of al1.

To print the elements of the array objArray, instead of using a for loop, simple toString() method of java.util.Arrays is used.

Still if you need a string array, convert object array to string array as follows.

   String stringArray[] = new String[objArray.length];
   for(int i = 0; i < objArray.length; i++)
     stringArray[i] = (String) objArray[i];
   System.out.println("String array: " + Arrays.toString(stringArray));

Read to know the reverse way of converting an array into collection class.

Leave a Comment

Your email address will not be published.