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.
-
Import Statements:
- The program imports
java.util.Listandjava.util.ArrayListfor using theArrayListcollection.
- The program imports
-
Creation of an ArrayList:
- An
ArrayListnamedcountryListis created to store a list of countries. - It uses the generic type
<String>to specify that it will store strings only.
- An
-
Adding Elements:
- The
add()method is used to add country names like "India", "Australia", "France", and "Germany" to thecountryList.
- The
-
Displaying ArrayList:
- The
ArrayListis printed directly usingSystem.out.println(countryList).
- The
-
Conversion from ArrayList to Array:
- The
toArray()method converts theArrayListinto a regular array:String[] countryArray = countryList.toArray(new String[countryList.size()]);
- A new
Stringarray of the same size as theArrayListis passed as an argument to thetoArray()method.
- The
-
Displaying the Array:
- The contents of the array are printed using a
forloop to iterate through each element.
- The contents of the array are printed using a
Output
From ArrayList:
[India, Australia, France, Germany]
From array:
India
Australia
France
Germany