Home  >  Article  >  Java  >  Can we convert Java array to list?

Can we convert Java array to list?

WBOY
WBOYforward
2023-09-02 09:29:081207browse

Can we convert Java array to list?

We can easily convert Java Array to List using Arrays.asList() method.

Syntax

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

Returns a fixed-size list backed by the specified array. (Changes to the returned list are "written" to the array.) This method is used in conjunction with Collection.toArray() to act as a bridge between array-based and collection-based APIs. The returned list is serializable and implements RandomAccess.

Type parameters

  • T - The runtime type of

Parameters

  • a - Array lists will be supported.

Returns a list view of the

specified array.

Example

The following example demonstrates how to use the Arrays.asList() method to obtain immutable and mutable lists.

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 results -

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)

The above is the detailed content of Can we convert Java array to list?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:tutorialspoint.com. If there is any infringement, please contact admin@php.cn delete