Common Pitfalls When Using Arrays.asList in Java
This article explains why using Java's Arrays.asList with primitive arrays can produce unexpected list sizes, why the resulting list is immutable, and provides correct usage patterns with code examples to avoid UnsupportedOperationException and other bugs.
In Java development, Arrays.asList is often used to convert an array to a List, but it has several hidden pitfalls that can lead to surprising behavior.
1. Do not pass primitive type arrays directly to asList
When a primitive int[] is passed, the method treats the whole array as a single element, so the resulting list has size 1 instead of the expected number of elements.
public static void main(String[] args) {
int[] ints = {1,2,3,4,5};
List list = Arrays.asList(ints);
System.out.println("list'size:" + list.size());
}The output shows list'size:1 because the list contains the original int[] object. The source of asList reveals that the method accepts a generic var‑args parameter, which cannot be instantiated with primitive types; the array itself is treated as a single generic element.
To obtain a proper list of integers, use the wrapper type Integer[] instead:
public static void main(String[] args) {
Integer[] ints = {1,2,3,4,5};
List list = Arrays.asList(ints);
System.out.println("list'size:" + list.size());
System.out.println("list.get(0) 的类型:" + list.get(0).getClass());
System.out.println("list.get(0) == ints[0]:" + list.get(0).equals(ints[0]));
}This correctly prints a size of 5 and shows that each element is an Integer.
2. The list returned by asList is immutable
Attempting to modify the list (e.g., list.add(6)) throws UnsupportedOperationException because the underlying implementation is a private static class inside Arrays that extends AbstractList and overrides mutating methods to always throw this exception.
public static void main(String[] args) {
Integer[] ints = {1,2,3,4,5};
List list = Arrays.asList(ints);
list.add(6); // throws UnsupportedOperationException
}The source code of this internal ArrayList class confirms that methods such as add, set, and remove are implemented to throw UnsupportedOperationException, making the list fixed‑size.
Therefore, when using Arrays.asList, avoid passing primitive arrays and do not attempt to modify the returned list; if a mutable list is needed, create a new ArrayList from the result, e.g., new ArrayList<>(Arrays.asList(...)).
— THE END —
Signed-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
Big Data Technology & Architecture
Wang Zhiwu, a big data expert, dedicated to sharing big data technology.
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.
