How to convert an ArrayList to array in Java
November 25, 2009
Today, I will share a very basic Java program that converts an ArrayList to an array. For most Java developers this is a routine task, but many newcomers 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<String> list = new ArrayList<String>();
//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<String> list2 = Arrays.asList(array);
A more modern way to do the conversion (Java 11+)
The example above pre-sizes the target array (new String[list.size()]) before calling toArray. Since Java 11 you can skip that and let toArray allocate the correctly-sized array itself with a method reference — it’s shorter and, according to the JDK’s own Collection.toArray docs, actually faster in most cases because the JVM can generate the array directly via reflection instead of the caller pre-allocating one:
String[] array = list.toArray(String[]::new);
This still works exactly the same way on JDK 21.
Enjoy!