Avoid These 3 Common Pitfalls When Using Arrays.asList in Java
This article explains three hidden traps when converting arrays to lists with Arrays.asList—issues with primitive arrays, unsupported add/remove operations, and shared‑array side effects—and provides practical solutions using wrapper types, streams, or creating a new ArrayList.
Java 8 streams make collection operations concise, so developers often convert arrays to List for stream processing using Arrays.asList. However, this method has several pitfalls.
Pitfall 1: Cannot directly use Arrays.asList with primitive arrays
First Pitfall
Given an int[] of three numbers, converting it with Arrays.asList produces a list containing a single element—the whole int[] —instead of three integers.
The reason is that generic var‑args treat the primitive array as a single object, so the list’s element type becomes int[].
Solutions:
Use the wrapper type array, e.g., Integer[] instead of int[].
In Java 8+, use Arrays.stream(arr).boxed().collect(Collectors.toList()) to obtain a proper List<Integer>.
Second Pitfall
When converting a String[] to a list and attempting list.add("4"), an UnsupportedOperationException is thrown. UnsupportedOperationException This occurs because Arrays.asList returns a fixed‑size list backed by an internal ArrayList class that does not override add, inheriting the exception‑throwing implementation from AbstractList.
Third Pitfall
Modifying the original array after calling Arrays.asList also changes the list’s contents, since the list shares the same underlying array.
The internal ArrayList directly references the original array, leading to unintended side effects.
Solution: Decouple the list from the array by creating a new ArrayList, e.g., new ArrayList<>(Arrays.asList(arr)). This produces an independent list that supports add/remove operations without affecting the original array.
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.
Su San Talks Tech
Su San, former staff at several leading tech companies, is a top creator on Juejin and a premium creator on CSDN, and runs the free coding practice site www.susan.net.cn.
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.
