Convert an Array to Array List in Java

Last Updated On Sunday 27th Mar 2022

Array to ArrayList

Using Arrays.asList() method

  • Returns a fixed-size list backed by the specified array.
  • This method also provides a convenient way to create a fixed-size list initialized to contain several elements.
  • The returned list is serializable and implements RandomAccess.
  • Type Parameters
    T – the class of the objects in the array
  • Parameters
    a – the array by which the list will be backed
  • Returns
    a list view of the specified array
	List<String> stooges = Arrays.asList("Larry", "Moe", "Curly");
	
	import java.util.*;

public class Main {
    public static void main (String[] args) {

        String[] names = { "Adam", "Ben", "Sam", "Nero" };

        List liNames = Arrays.asList(names);

        System.out.println(liNames);
    }
}
	
	[Adam, Ben, Sam, Nero]
	

Java Array to ArrayList

  • List is fixed-size List, we can’t add more element.
  • Create new ArrayList and pass Arrays.asList as an argument to it.
	import java.util.*;

public class Main {
    public static void main (String[] args) {
        String[] names = { "Adam", "Alice", "Ben", "Nero" };

        List<String> al = new ArrayList<String>(Arrays.asList(names));
        System.out.println(al);

        al.add("Sam");
        al.add("Tommy");

        System.out.println("\nArrayList After add");
        System.out.println(al);
    }
}
	
	// [Adam, Alice, Ben, Nero]

// ArrayList After add
// [Adam, Alice, Ben, Nero, Sam, Tommy]
	

Using Collections.addAll() method

  • Adds all of the elements in the specified collection to this collection.
	boolean addAll(Collection<? extends E> c)
	
  • Parameters:
    c – collection containing elements to be added to this collection
  • Returns
    true if this collection changed as a result of the call

Array to ArrayList Java

	import java.util.*;

public class Main {
    public static void main (String[] args) {
        String[] names = { "Adam", "Alice", "Ben", "Nero" };

        List<String> al = new ArrayList<String>();
        Collections.addAll(al, names);
        System.out.println(al);
    }
}
	
	// [Adam, Alice, Ben, Nero ]
	

Using Array using add() method

	public boolean add(E e)
	

Convert Array to ArrayList

  • Appends the specified element to the end of this list.
  • Parameters
    e – element to be appended to this list
  • Returns
    true (as specified by Collection.add(E))
	import java.util.*;
public class Main {
    public static void main (String[] args) {
        String[] names = { "Adam", "Alice", "Ben", "Nero" };

        List<String> al = new ArrayList<String>();

        for (String name : names)
            al.add(name);

        System.out.println(al);
    }
}
	
	// [Adam, Alice, Ben, Nero ]