Common Pitfalls When Using Java List Collections
The article explains three typical traps when working with Java List: Arrays.asList returns a fixed‑size list that throws UnsupportedOperationException on add/remove, iterating and removing elements directly also fails, and converting primitive arrays with Arrays.asList produces an unexpected single‑element list.
Background
List is a collection frequently used in Java development, but it has its own limitations and errors. The following sections illustrate common pitfalls.
Arrays.asList returns a List that does not support add or remove operations
String[] array = new String[]{"a","b","c"};
System.out.println(array.length);
List<string> strings = Arrays.asList(array);
strings.add("d");
strings.remove(1);Both add and remove cause java.lang.UnsupportedOperationException because the list returned by Arrays.asList is not a regular ArrayList but a fixed‑size view.
Directly iterating a List and removing elements also throws an error
String[] array = new String[]{"a","b","c"};
System.out.println(array.length);
List<string> strings = Arrays.asList(array);
for (int i = 0; i < strings.size(); i++) {
strings.remove(i);
}Removing elements while iterating over the list produced by Arrays.asList triggers the same UnsupportedOperationException.
Unexpected behavior when converting primitive arrays with Arrays.asList
When developers need to convert an array to a List, they often use Arrays.asList. However, for primitive type arrays the result is not what is expected.
int[] array = new int[]{1,2,3};
System.out.println(array.length);
List<int[]> ints = Arrays.asList(array);
System.out.println(ints.size());The printed results are 3 and 1. The list contains a single element of type int[], meaning the whole primitive array is treated as one object rather than being split into individual integers.
These examples demonstrate why developers should be cautious when using Arrays.asList with mutable operations or primitive arrays.
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.
Coder Trainee
Experienced in Java and Python, we share and learn together. For submissions or collaborations, DM us.
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.
