Java Program to convert ArrayList to Array

Program

import java.util.List;
import java.util.ArrayList;
public class ArrayListToArrayDemo
{
    public static void main(String[] args)
    {
        List<String> countryList = new ArrayList<String>();
        countryList.add("India");
        countryList.add("Australia");
        countryList.add("France");
        countryList.add("Germany");
        System.out.println("From ArrayList:");
        System.out.println(countryList);
        String[] countryArray = countryList.toArray(new String[countryList.size()]);
        System.out.println("From array:");
        for(int i = 0; i < countryArray.length; i++)
            System.out.println(countryArray[i]);
    }
}

This Java program demonstrates how to convert an ArrayList to an array using the toArray() method.

  1. Import Statements:

    • The program imports java.util.List and java.util.ArrayList for using the ArrayList collection.
  2. Creation of an ArrayList:

    • An ArrayList named countryList is created to store a list of countries.
    • It uses the generic type <String> to specify that it will store strings only.
  3. Adding Elements:

    • The add() method is used to add country names like "India", "Australia", "France", and "Germany" to the countryList.
  4. Displaying ArrayList:

    • The ArrayList is printed directly using System.out.println(countryList).
  5. Conversion from ArrayList to Array:

    • The toArray() method converts the ArrayList into a regular array:
      • String[] countryArray = countryList.toArray(new String[countryList.size()]);
    • A new String array of the same size as the ArrayList is passed as an argument to the toArray() method.
  6. Displaying the Array:

    • The contents of the array are printed using a for loop to iterate through each element.

Output

From ArrayList:
[India, Australia, France, Germany]
From array:
India
Australia
France
Germany