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

Can we convert Java array to list?

WBOY
Release: 2023-09-02 09:29:08
forward
1228 people have browsed it

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)
Copy after login

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);
   }
}
Copy after login

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)
Copy after login

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!

Related labels:
source:tutorialspoint.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template