Java Arrays.asList() Example - Convert Array to ArrayList

Java Arrays.asList() method returns a fixed-size list backed by the specified array. In this example, we use the asList() method to convert Array to ArrayList.

Java Arrays.asList() Example - Convert Array to ArrayList

In this example, we will convert String Array to ArrayList of String type.
import java.util.Arrays;
import java.util.List;

/**
 * This class shows different methods to convert Array to ArrayList
 * 
 * @author javaguides.net
 *
 */
public class ArrayToArrayList {

        public static void main(String[] args) {
                String anArrayOfStrings[] = { "Agra", "Mysore", "Chandigarh", "Bhopal" };

                List<String> strList = Arrays.asList(anArrayOfStrings);

                System.out.println("Original ArrayList from Arrays.asList()");

                /* Display array list */
                strList.forEach(str -> System.out.println(" " + str));

                // change the array element and see the effect is propogated to list
                // also.
                anArrayOfStrings[0] = "Dehli";

                System.out.println("\nChange in array effect on ArrayList");

                /* Display array list */
                strList.forEach(str -> System.out.println(" " + str));
        }

}
Output:
Original ArrayList from Arrays.asList()
 Agra
 Mysore
 Chandigarh
 Bhopal

Change in array effect on ArrayList
 Dehli
 Mysore
 Chandigarh
 Bhopal
Let's see one more example, convert Integer Array to ArrayList of Integer type.
Integer anArrayOfIntegers[] = { 1,2,3,4,5,6 };

List<Integer> intList = Arrays.asList(anArrayOfIntegers);

/* Display array list */
intList.forEach(str -> System.out.println(" " + str));
Output:
 1
 2
 3
 4
 5
 6

Reference

Comments