How to Convert ArrayList to Array in Java?
While developing Java applications I have to convert ArrayList to Array lots of time. This is a very simple task and does not need any iterations, but I have seen most of the developers end up in iterating the list to create the array. So I thought of sharing this piece of code which converts ArrayList to Array in a single line.
ArrayList class has a method toArray() which can be used to convert to Array and here in this example we are using the same method.
Java Code to Convert ArrayList to Array
public class ConvertArrayListToArray
public static void main(String args)
List<String> list = new ArrayList<String>();
//toArray() adjusts the size automatically
//So you just need to initialize it with 0
String array = list.toArray(new String);
//Print the array
[Test1, Test2, Test3, Test4]
To Generalise: To convert ArrayList of any class to Array use the below code. Just replace T with the class you want to create arrays.
T array = list.toArray(new T);
This code will work for any kind of ArrayLists.