Java ArrayList to Array


Java ArrayList to Array

Summary: After seeing the 4 styles of converting array elements into array list, now let us do the opposite way of converting "Java ArrayList to Array".

Note: There are two methods, asList() and toArray(), that bridges collection classes (data structures) and array. These methods are defined in Arrays class and Collection interface (inherited by List interface).

The following program illustrates toArray() method in converting Java ArrayList to Array.

import java.util.*;
public class ArrayListToArray
{
 public static void main(String args[])
 {		                                  // CREATING ARRAYLIST
   ArrayList al1 = new ArrayList();
   al1.add("judiciary");  al1.add("is");  al1.add("supreme");
   System.out.println("ArrayList elements: " + al1);

		                                  // CONVERTING TO OBJECT ARRAY
   Object obj[] = al1.toArray();
   System.out.print("Object array: ");
   for(Object o1 : obj)
   {
     System.out.print(o1 + " ");
   }		                                  // CONVERTING OBJECT ARRAY TO STRING ARRAY
   String country[] = new String[obj.length];
   for(int i = 0; i < country.length; i++)
   {
     country[i] = (String) obj[i];
   }
   System.out.println("\ncountry string array: " + Arrays.toString(country));
 }
}

Java ArrayList to Array

      ArrayList al1 = new ArrayList();
      al1.add("judiciary");  al1.add("is");  al1.add("supreme");

An array list object al1 is created and added 3 elements with add() method.

     Object obj[] = al1.toArray();
     for(Object o1 : obj)
     {
       System.out.print(o1 + " ");
     }

The toArray() method of List (inherited from Collection interface) interface returns an Object array with all the elements of array list al1. Using the enhanced for loop (commonly known as foreach loop), all the elements of the array are printed.

     System.out.println(Arrays.toString(obj));

Alternatively, the above for loop can be avoided using toString() method of Arrays class to print the elements of the array (not shown in the program).

The Object array can be converted into a string array as follows, if required in the code.

   
     String country[] = new String[obj.length];
     for(int i = 0; i < country.length; i++)
     {
       country[i] = (String) obj[i];
     }

Explicit casting is done to convert object of Object class to String class.

Array related topics that increase array manipulation techniques

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

Pass your suggestions to improve the quality of this tutorial "Java ArrayList to Array".

Leave a Comment

Your email address will not be published.