Way2Java

Array to List Java

Here we use asList() method of class Arrays.

Following is the method signature

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");
  }
}


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)