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

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s