Today, I will share a very basic Java program that converts an ArrayList to array. For most Java developers this is a routine task, but many new comers to Java have asked me this question of how to convert an array to ArrayList. Here is the example code.
import java.util.*;
public class ArrayToArrayList{
public static void main(String args[]){
//Create an ArrayList of Strings.
ArrayList list = new ArrayList();
//Populate the ArrayList.
list.add("A1");
list.add("A2");
list.add("A3");
list.add("A4");
list.add("A5");
list.add("A6");
/*Initialize a String array.
Set array's capacity equal to ArrayList size*/
String[] array = new String[list.size()];
//Now get the array from ArrayList. There is no magic here.
//We are calling toArray method of the ArrayList class.
array = list.toArray(array);
}
}
How to convert a Java Array to a List
In some instances you may need to convert an array to a list. This is also a simple task. Using the array variable defined in the example above, we can call asList method of the Arrays class to get a List variable from the array.
List list2 = Arrays.asList(array);
Enjoy!