On this section we will be discussing regarding java array to arraylist conversion. At the end of this tutorial we would shed light on how to handle the conversion of array to arraylist and how to print the contents of an arraylist by using advance for loop (for each). The conversion is easy we just have to call the static asLList method of java.util.Arrays class.

Supposed we have an array of Strings, convert it into List. After conversion verify the elements the array contains by printing it through the console.

Java array to arraylist conversion – Using the asList method

package com.javatutorialhq.tutorial;

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

// Java array to arraylist example source code

public class ArrayConversion {

	public static void main(String[] args) {
		String[] arrayString = new String[]{"edward","anne","mary"};
		List alist = new ArrayList();
		alist = Arrays.asList(arrayString);
		System.out.println("Printing the contents of the list");
		for(String elementList : alist){
			System.out.println(elementList);
		}
	}

}

Sample Output:

edward
anne
mary

As you can see from the source code provided, the asList method makes our life easier.

Java array to arraylist conversion – Using for loop

Above method is the best solution however if you prefer a long method, we can always iterate through the elements of your array and then assign it one by one to the List by calling the add method.

package com.javatutorialhq.java.examples;

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

/*
 * This example source code demonstrates how 
 * to convert array to arraylist
 */

public class ArrayToArrayListConverter {

	public static void main(String[] args) {
		
		// declaring the contents of our array
		String[] arrayString = new String[]{"apple","mango","pineapple","durian"};
		// instantiate list object
		List alist = new ArrayList();
		for(String s:arrayString){
			// adding each element of array
			// as member to our list
			alist.add(s);
		}
		//printing the contents of our list
		for(String s:alist){
			System.out.println(s);
		}		
		
	}

}

Sample Output

Running above example will give the following output

Java array to arraylist conversion example

Java array to arraylist conversion example