Thursday, August 25, 2011

Convert ArrayList to Array in Java. ArrayList to Array. Java Collection

A lot of time I have to convert ArrayList to Arrays in my Java program. Although this is a simple task, many people don’t know how to do this and end up in iterating the java.util.ArrayList to convert it into arrays. I saw such code in one of my friends work and I thought to share this so that people don’t end up writing easy thing in complicated way.


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 list = new ArrayList;

list.add("India");
list.add("Switzerland");
list.add("Italy");
list.add("France");
String [] countries = list.toArray(new String[0]);


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

List list = new ArrayList;

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:



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

No comments:

Post a Comment