Write a Java program to Convert an ArrayList to Array


This Java program demonstrates how to convert an ArrayList to an array. Here's how the code works:

  • An ArrayList named fru_list of type String is created and several fruits are added to it using the add() method.
  • The elements of the ArrayList are displayed using the println() method.
  • An empty array of type Object is created.
  • The toArray() method of the ArrayList is called, which returns an array containing all the elements of the ArrayList.
  • The elements of the array are displayed using a for-each loop.

Note that the toArray() method returns an array of type Object, so if the ArrayList contains elements of a specific type, you will need to cast the elements to that type after converting the ArrayList to an array.

Source Code

import java.util.ArrayList;
public class ArrayList_ToArray
{
    public static void main(String[] args)
    {
		ArrayList<String> fru_list = new ArrayList<String>();
		fru_list.add("Papaya");
		fru_list.add("Mulberry");
		fru_list.add("Apple");
		fru_list.add("Banana");
		fru_list.add("Cherry");
		fru_list.add("Watermelon"); 
		System.out.println("ArrayList : "+fru_list);
		System.out.println("\nConvert an ArrayList to Array ..");
 
		Object[] arr = fru_list.toArray();
 
		for (Object obj : arr)
		{
			System.out.println(obj);
		}
    }
}

Output

ArrayList : [Papaya, Mulberry, Apple, Banana, Cherry, Watermelon]

Convert an ArrayList to Array ..
Papaya
Mulberry
Apple
Banana
Cherry
Watermelon

Example Programs