Array to List Java

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.

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.


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

Leave a Reply

Your email address will not be published. Required fields are marked *