Java, How to convert List to Arrays and Array to ArrayList


In our day to day programming sometime use this conversion by using iteration but there is another way by using Java API’s as below.

ArrayList to Arrays

List provide toArray() method to convert list elements in Arrays.

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

Example :

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

public class ConvertArrayListToArray {

	public static void main(String[] args) {
		List<String> list = new ArrayList<String>();
		list.add("Georgia");
		list.add("Texas");
		list.add("Newyork");
		list.add("Okhlama");
		String [] states = list.toArray(new String[list.size()]);
	}

}

Arrays to ArrayList

Arrays class provide to asList() method to convert Array to immutable List So if you need to modify anything in List you will get java.lang.UnsupportedOperationException.

If you want to modification after convert to List then create with new ArrayList as below.

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

public class ConvertArrayToArrayList {

	public static void main(String[] args) {
		String [] states= {"Georgia","Texas","New York", "Okhlama"};
		//Convert Array to immutable List
         List<String> stateList= Arrays.asList(states);
         try
         {
         stateList.add("North Carolina");
         }
         catch(UnsupportedOperationException ex)
         {
        	 ex.printStackTrace();
         }

         //Convert Array to mutable List
         stateList=new ArrayList<String>(Arrays.asList(states));
         stateList.add("North Carolina");
         System.out.println(stateList.get(4));
	}

}

In above example I have considered both cases for Immutable and Mutable.

More Sample Code

For more java and JDBC codes follow below links

About Saurabh Gupta

My Name is Saurabh Gupta, I have approx. 10 Year of experience in Information Technology World manly in Java/J2EE. During this time I have worked with multiple organization with different client, so many technology, frameworks etc.
This entry was posted in Java, Uncategorized and tagged , , , , , , . Bookmark the permalink.