Common Pitfalls When Converting Arrays to Lists with Arrays.asList in Java
This article explains three common pitfalls of using Java's Arrays.asList—its incompatibility with primitive arrays, the immutability of the returned list, and the shared backing array that causes side‑effects—along with practical solutions such as using wrapper types, Streams, or creating a new ArrayList.
Java 8's Stream API encourages developers to convert arrays to List objects for easier processing, and Arrays.asList is the most frequently used shortcut. However, this method has three hidden pitfalls that can lead to subtle bugs.
Pitfall 1: Primitive arrays cannot be directly converted
When an int[] is passed to Arrays.asList , the method treats the whole array as a single element, resulting in a list of size 1 whose sole element is the original int[] . This occurs because the var‑args parameter expects objects, and a primitive array is boxed as a single object.
Two ways to fix this are:
Declare the array with the wrapper type ( Integer[] ) instead of the primitive type.
In Java 8+ use Arrays.stream(array).boxed().collect(Collectors.toList()) , which converts each primitive to its wrapper and builds a proper list.
Pitfall 2: The returned list does not support add/remove operations
The list produced by Arrays.asList is not a regular java.util.ArrayList but an internal static class that extends AbstractList . Its add and remove methods are not overridden, so they throw UnsupportedOperationException .
Because of this, attempts to modify the list (e.g., adding a new element) will fail.
Pitfall 3: Modifying the original array affects the list
The list returned by Arrays.asList shares the original array as its backing store. Any change to the array after conversion is reflected in the list, and vice‑versa.
This shared‑reference behavior can cause unexpected side‑effects when the list is passed to other methods.
Recommended solution
To avoid all three issues, create a new mutable ArrayList from the result of Arrays.asList :
List<String> mutableList = new ArrayList<>(Arrays.asList(originalArray));This decouples the list from the original array, provides full mutability, and works with both primitive wrapper arrays and object arrays.
IT Services Circle
Delivering cutting-edge internet insights and practical learning resources. We're a passionate and principled IT media platform.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.