We can easily convert Java Array to List using Arrays.asList() method.
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.
T - The runtime type of
a - Array lists will be supported.
specified array.
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); } }
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!