Fundamentals 4 min read

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.

Coder Trainee
Coder Trainee
Coder Trainee
Common Pitfalls When Using Java List Collections

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.

Original Source

Signed-in readers can open the original source through BestHub's protected redirect.

Sign in to view source
Republication Notice

This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactadmin@besthub.devand we will review it promptly.

JavaCollectionsArrays.asListListUnsupportedOperationExceptionprimitive array
Coder Trainee
Written by

Coder Trainee

Experienced in Java and Python, we share and learn together. For submissions or collaborations, DM us.

0 followers
Reader feedback

How this landed with the community

Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.