In this post under Java Collections, I will explain with example how to convert an array to list.
Please note this conversion is possible if the array is a collection of objects and not primitive elements.
To achieve our goal, we use “Arrays” class static method “asList”. This method returns a list backed by the array.
Please note modifying the existing elements of an array will also affect the List. The reverse is also true.
Below is the complete main code for your reference.
Main class
1 package core.collection;
2
3 import java.util.Arrays;
4 import java.util.List;
5
6 public class ArraysToListDemo {
7 public static void main(String[] args) {
8 Integer[] intArray = new Integer[]{1, 2, 3, 4, 5};
9 List<Integer> integerList = Arrays.asList(intArray);
10
11 System.out.println("List output: " + integerList);
12
13 intArray[2] = 6;
14
15 System.out.println("List output after modification to array: " + integerList);
16
17 integerList.set(2, 7);
18
19 String output = Arrays.toString(intArray);
20
21 System.out.println("Array output after modification to list: " + output);
22 }
23 }
In the above code, at line 8, I create an array of type “Integer” and populate it with elements.
At line 9, I call “Arrays” class “asList” method and pass the array as an argument.
This “asList” method returns a “List” of type “Integer” with elements same as in the array.
In this way we can convert a array to List.
At line 13, I modify the array, by setting the element at position 2 to 6 from 3.
This change is reflected in the list also.
At line 17, I modify the list, by setting the element at position 2 to 7 from 6.
This change is relected in the array also.
Below is the output.
Output
List output: [1, 2, 3, 4, 5]
List output after modification to array: [1, 2, 6, 4, 5]
Array output after modification to list: [1, 2, 7, 4, 5]