Array to List Java

Here we use asList() method of class Arrays.

Following is the method signature

  • static List asList(T array): The method returns a List object with all the elements of the array. The list returned is fixed size. That is, you cannot add further elements to the list.
Following example on "Array to List Java" with asList() illustrates.
import java.util.Arrays;
import java.util.List;
public class ArrayToList
  public static void main(String[] args) 
    String cityArray[] = { "Hyderabad", "Chennai", "Pune" };
    System.out.println("Array cityArray elements: " + Arrays.toString(cityArray));
    List cityList = Arrays.asList(cityArray);
    System.out.print("cityList elements: " + cityList);

    // cityList.add("Mumbai");    // if comments removed, throws UnSupportedOperationException
    // cityList.remove("Delhi");

Array to List Java
Output screenshot on Array to List Java

String cityArray[] = { “Hyderabad”, “Chennai”, “Pune” };
System.out.println(“Array cityArray elements: ” + Arrays.toString(cityArray));

A string array cityArray is done having three elements "Hyderabad", "Chennai" and "Pune". The elements are shown using toString(). toString() method of Arrays class is the easiest way to display the elements of an array.

List cityList = Arrays.asList(cityArray);
System.out.print(“cityList elements: ” + cityList);

Using static method asList(cityArray) of Arrays class, the elements are converted to List cityList elements.

The cityList is of fixed size. That is, further elements cannot be added. If added, JVM raises an unchecked exception UnSupportedOperationException.

Output screenshot when further elements are added (of Array to List Java)

Leave a Comment

Your email address will not be published.