Can we convert a Java array to list?

JavaObject Oriented ProgrammingProgramming

We can use Arrays.asList() method to convert a Java array to List easily.

Syntax

public static <T> List<T> asList(T... a)

Returns a fixed-size list backed by the specified array. (Changes to the returned list "write through" to the array.) This method acts as bridge between array-based and collection-based APIs, in combination with Collection.toArray(). The returned list is serializable and implements RandomAccess.

Type Parameter

  • − The runtime type of the array.

Parameters

  • − The array by which the list will be backed.

Returns

A list view of the specified array.

Example

The following example shows how to get immutable and mutable list using Arrays.asList() method.

package com.tutorialspoint;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

public class CollectionsDemo {
   public static void main(String[] args) {
      Integer[] array = {1,2,3,4,5,6};

      // Get a mutable list from array
      List<Integer> list = new ArrayList<>(Arrays.asList(array));
      list.add(7);
      System.out.println("List: " + list);

      // Get immutable list from array
      List<Integer> list1 = Arrays.asList(array);
      try {
         list1.add(7);
      } catch(Exception e) {
         e.printStackTrace();
      }
      System.out.println("List: " + list1);
   }
}

Output

This will produce the following result −

List: [1, 2, 3, 4, 5, 6, 7] 
List: [1, 2, 3, 4, 5, 6] 
java.lang.UnsupportedOperationException 
   at java.util.AbstractList.add(AbstractList.java:148) 
   at java.util.AbstractList.add(AbstractList.java:108) 
   at com.tutorialspoint.CollectionsDemo.main(CollectionsDemo.java:19)
raja
Updated on 09-May-2022 11:54:44

Advertisements