Convert array to List with asList()

Arrays.asList() converts all the elements of the array into a List. It is the easiest way to pass the elements of an array to a List; an interoperability feature between arrays and collections framework classes. Convert array to List with asList()

Following is the method signature

  • static List asList(T array): It is useful to convert an array into a List. The method returns a List object with the elements of the array and further elements cannot be added to the list. Useful to have fixed size list on which add() and remove() methods do not work. Overloaded to take any data type array as parameter.
Following example on Convert array to List with asList() illustrates.
import java.util.Arrays;
import java.util.List;
public class ArraysAsList
{
  public static void main(String[] args) 
  {
    String stones1[] = { "diamond", "ruby", "emerald" };
    System.out.println("Array stones1 elements: " + Arrays.toString(stones1));
    
    List myList = Arrays.asList(stones1);
    System.out.print("\nmyList elements: " + myList);

    // myList.add("topaz");
    // myList.remove("ruby");
  }
}


Convert array to List with asList()
Output screenshot on Convert array to List with asList()

String stones1[] = { “diamond”, “ruby”, “emerald” };
System.out.println(“Array stones1 elements: ” + Arrays.toString(stones1));

A string array stones1 is created with three elements "diamond", "ruby" and "emerald" and the elements are displayed with toString() method. toString() method of Arrays class is the easiest way to display the elements of an array.

List myList = Arrays.asList(stones1);
System.out.print(“\nmyList elements: ” + myList);

To create a List object with the elements of the array stones1, the array object is passed to asList() method.

// myList.add(“topaz”);
// myList.remove(“ruby”);

The List object myList returned by asList() method is immutable. That is, it is of fixed size and further addition or removal of elements raises UnsupportedOperationException. For this reason, the above lines are placed in comments in the code.

It is nearer to addAll() of Collections. It is also possible to convert "array list elements to array".

One more program is available at "Array to ArrayList" for further reference. Comparison with array list is available at "Array vs ArrayList".

Leave a Comment

Your email address will not be published.