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.List
andjava.util.ArrayList
for using theArrayList
collection.
- The program imports
-
Creation of an ArrayList:
- An
ArrayList
namedcountryList
is 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
ArrayList
is printed directly usingSystem.out.println(countryList)
.
- The
-
Conversion from ArrayList to Array:
- The
toArray()
method converts theArrayList
into a regular array:String[] countryArray = countryList.toArray(new String[countryList.size()]);
- A new
String
array of the same size as theArrayList
is passed as an argument to thetoArray()
method.
- The
-
Displaying the Array:
- The contents of the array are printed using a
for
loop 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