Let’s see the below example to convert ArrayList to Array and Array to ArrayList in Java:
import java.util.*;
public class Main
{
public static void main(String[] args)
{
//creating Arraylist
List<String> carList = new ArrayList<>();
//adding String Objects to carList ArrayList
carList.add("Mercedes");
carList.add("Range Rover.");
carList.add("Roll-Royce");
carList.add("Bentley");
carList.add("Porsche");
carList.add("BMW ");
carList.add("Audi");
System.out.println("Convert ArrayList elements to Array" );
String[] elements = carList.toArray(new String[carList.size()]);
for(String str : elements)
{
System.out.println(str);
}
System.out.println("Convert Array elements to ArrayList" );
List<String>clist = new ArrayList<>();
clist = Arrays.asList(elements);
System.out.println(clist);
}
}
Output:-
Convert ArrayList elements to Array Mercedes Range Rover. Roll-Royce Bentley Porsche BMW Audi Convert Array elements to ArrayList [Mercedes, Range Rover., Roll-Royce, Bentley, Porsche, BMW , Audi]