Java How to Convert Array to List with Examples
Arrays.asList(array), which returns a fixed-size list backed by the array.Examples
How to Think About It
Arrays.asList() that takes the array and returns a list view of it.Algorithm
Code
import java.util.Arrays; import java.util.List; public class ArrayToListExample { public static void main(String[] args) { String[] fruits = {"apple", "banana", "cherry"}; List<String> fruitList = Arrays.asList(fruits); System.out.println(fruitList); } }
Dry Run
Let's trace converting the array ["apple", "banana", "cherry"] to a list.
Input array
fruits = ["apple", "banana", "cherry"]
Convert using Arrays.asList
fruitList = Arrays.asList(fruits) -> [apple, banana, cherry]
Print the list
Output: [apple, banana, cherry]
| Step | Action | Value |
|---|---|---|
| 1 | Input array | ["apple", "banana", "cherry"] |
| 2 | Convert to list | [apple, banana, cherry] |
| 3 | Print list | [apple, banana, cherry] |
Why This Works
Step 1: Arrays.asList creates a list view
The method Arrays.asList() wraps the array into a fixed-size list without copying elements.
Step 2: List reflects array changes
Changes to the array will reflect in the list and vice versa because they share the same data.
Step 3: List size is fixed
You cannot add or remove elements from the list returned by Arrays.asList() because its size is fixed.
Alternative Approaches
import java.util.ArrayList; import java.util.Arrays; import java.util.List; public class ArrayToListAlt { public static void main(String[] args) { String[] fruits = {"apple", "banana", "cherry"}; List<String> fruitList = new ArrayList<>(Arrays.asList(fruits)); System.out.println(fruitList); } }
import java.util.Arrays; import java.util.List; import java.util.stream.Collectors; public class ArrayToListStream { public static void main(String[] args) { String[] fruits = {"apple", "banana", "cherry"}; List<String> fruitList = Arrays.stream(fruits).collect(Collectors.toList()); System.out.println(fruitList); } }
Complexity: O(n) time, O(1) or O(n) depending on method space
Time Complexity
Converting an array to a list takes O(n) time because each element is referenced or copied once.
Space Complexity
Using Arrays.asList() uses O(1) extra space as it wraps the array, but creating a new ArrayList copies elements, using O(n) space.
Which Approach is Fastest?
Arrays.asList() is fastest and uses least memory but returns a fixed-size list. Creating a new ArrayList is slower but allows modification.
| Approach | Time | Space | Best For |
|---|---|---|---|
| Arrays.asList() | O(n) | O(1) | Quick conversion, fixed-size list |
| new ArrayList<>(Arrays.asList()) | O(n) | O(n) | Modifiable list |
| Streams with Collectors.toList() | O(n) | O(n) | Flexible processing and modifiable list |
Arrays.asList(array) for quick conversion but wrap with new ArrayList<>(...) if you need a modifiable list.Arrays.asList() causes an UnsupportedOperationException.