How to convert ArrayList to Array and Array to ArrayList?

Arrays class provide method Arrays.asList()  which convert array type elements to a unmodified fixed size ArrayList.

Same way List provide method as List.toArray(List) which convert ArrayList elements to Array.

Note : List returned from Arrays.AsList() is not like java.util.ArrayList. It
returns a java.util.Arrays$ArrayList which is an immutable list. You can not add or remove any element from this list otherwise will get java.lang.UnsupportedOperationException

Example : 

In below example used method Arrays.asList()  to convert  String array to ArrayList of String elements. On other  side use List.toArray() method to convert ArrayList elements to Arrays of type String elements.

package exceptionhandeling;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

public class ArrayToArrayListConversion {

	public static void main(String[] args) {
		String [] empArr={"Saurabh","Gaurav","Shailesh","Ankur","Ranjith","Ramesh"};
		//Convert Array to LIst
		List empList=Arrays.asList(empArr);
		System.out.println("*****Print ArrayList*****");
		printArrayList(empList);
		//Convert ArrayList to Array
		 empArr=(String[])empList.toArray();
		 System.out.println("*****Print Array*****");
		 printArray(empArr);
	}
	private static void printArrayList(List empList)
	{
		for(String emp:empList)
		{
			System.out.println(emp);
		}
	}
	private static void printArray(String[] empArr)
	{
		for(String emp:empArr)
		{
			System.out.println(emp);
		}
	}
}

Output:

*****Print ArrayList*****
Saurabh
Gaurav
Shailesh
Ankur
Ranjith
Ramesh
*****Print Array*****
Saurabh
Gaurav
Shailesh
Ankur
Ranjith
Ramesh
Advertisements

This site uses Akismet to reduce spam. Learn how your comment data is processed.