Collection to Array Java

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.

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.

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

Leave a Reply

Your email address will not be published. Required fields are marked *