Friday, April 15, 2011

Convert ArrayList to Arrays in Java and vice-versa

ArrayList class has a method called toArray() that we are using in our example to convert it into Arrays.
Following is simple code snippet that converts an array list of countries into string array.

List<String> countryList= new ArrayList<String>();
 
countryList.add("India");
countryList.add("Switzerland");
countryList.add("Italy");
countryList.add("France");
 
String [] countries = list.toArray(new String[countryList.size()]);

So to convert ArrayList of any class into array use following code. Convert T into the class whose arrays you want to create.

List<T> list = new ArrayList<T>();
 
T [] countries = list.toArray(new T[list.size()]);

Convert Array to ArrayList

We just saw how to convert ArrayList in Java to Arrays. But how to do the reverse? Well, following is the small code snippet that converts an Array to ArrayList:

import java.util.ArrayList;
import java.util.List;
import java.util.Arrays;
 
...
 
String[] countries = {"India", "Switzerland", "Italy", "France"};
List list = new Arrays(Arrays.asList(countries));
System.out.println("ArrayList of Countries:" + list);

No comments:

Post a Comment

Chitika