List to Array Java


Here, toArray() method of Collections interface is used. This method returns an Object array containing the elements of collection class.

Example on on "List to Array Java" explains the usage of toArray() method to convert List to array.
import java.util.*;
public class ListConvertArray
{
 public static void main(String args[])
 {		                                  // CREATING LIST, ADDING ELEMENTS
   List cityList = new ArrayList();
   cityList.add("Vizag");  cityList.add("Hyderabad");  cityList.add("Tirupathi");
   System.out.println("List elements: " + cityList);

		                                  // CONVERTING LIST TO OBJECT ARRAY
   Object cityObjectArray[] = cityList.toArray();
   System.out.print("Object array elements: ");
   for(Object tempObj : cityObjectArray)
   {
     System.out.print(tempObj + " ");
   }		
                                                                    // CONVERTING OBJECT ARRAY TO STRING ARRAY (if needed)
   String cityStringArray[] = new String[cityObjectArray.length];
   for(int i = 0; i < cityStringArray.length; i++)
   {
     cityStringArray[i] = (String) cityObjectArray[i];
   }

   System.out.println("\nString array elements: " + Arrays.toString(cityStringArray));
 }
}


List to Array Java
Output screen on List to Array Java

List cityList = new ArrayList();
   cityList.add("Vizag");  cityList.add("Hyderabad");  cityList.add("Tirupathi");

A List object cityList is created and then added with three elements with add() method.

  Object cityObjectArray[] = cityList.toArray();
   System.out.print("Object array elements: ");
   for(Object tempObj : cityObjectArray)
   {
     System.out.print(tempObj + " ");
   }		
 

The List cityList object is converted to an object array with toArray() method defined in Collection interface (inherited by List interface), the super most interface of all DS of Java. Using enhanced for loop all the elements of object array cityObjectArray.

     Arrays.toString(cityStringArray)

All the elements of array cityStringArray are printed at a time (avoiding a loop iteration) with toString() method of class Arrays.

Java comes with many classes grouped as categories. Would you like to know?

Leave a Comment

Your email address will not be published.