How to convert an ArrayList to array in Java
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 list2 = Arrays.asList(array);
Enjoy!
December 10, 2009 @ 5:47 am
Nice, I just wished I had knew some java sense. 🙂
October 9, 2012 @ 11:31 pm
Arrays class is actually bridge between Array and ArrayList. you can also see here for couple of more ways to convert Array to ArrayList