Why Arrays.asList and subList Can Throw Unexpected Exceptions in Java
This article explains the hidden pitfalls of Java's Arrays.asList and ArrayList.subList methods, showing why add operations may trigger UnsupportedOperationException and how modifications to original or sub‑lists can cause ConcurrentModificationException, with code examples and visual illustrations.
1. Caution When Using Arrays.asList
1.1 Potential Pitfalls
First, see how Arrays.asList works:
List<Integer> statusList = Arrays.asList(1, 2);
System.out.println(statusList);
System.out.println(statusList.contains(1));
System.out.println(statusList.contains(3));The output is shown below:
Attempting to add an element:
statusList.add(3);
System.out.println(statusList.contains(3));Results in java.lang.UnsupportedOperationException because the list returned by Arrays.asList is a fixed‑size view backed by an internal ArrayList that does not override add.
Using the utility class Arrays.asList() to convert an array to a collection, you must not use modification methods such as add/remove/clear; they will throw UnsupportedOperationException .
1.3 Summary
Arrays.asListis convenient for quick list creation or range checks, but you must avoid calling modification methods like add on the resulting list.
2. Caution When Using ArrayList.subList
Simple usage example:
List<String> bookList = new ArrayList<>();
bookList.add("遥远的救世主");
bookList.add("背叛");
bookList.add("天幕红尘");
bookList.add("人生");
bookList.add("平凡的世界");
List<String> sub = bookList.subList(3, 5);
System.out.println(bookList);
System.out.println(sub);The result shows that subList returns a view of the original list from fromIndex (inclusive) to toIndex (exclusive).
Modifying the original list’s element values affects the sub‑list.
Structural modifications to the original list while iterating the sub‑list cause ConcurrentModificationException.
Modifying sub‑list element values affects the original list.
Structural modifications to the sub‑list affect the original list.
Examples and screenshots illustrate each case.
2.6 Summary
The subList method returns a view of the original collection; non‑structural changes to either list are reflected in the other, while structural changes can trigger ConcurrentModificationException or affect the original list. Use it carefully to avoid unexpected errors.
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.
Programmer DD
A tinkering programmer and author of "Spring Cloud Microservices in Action"
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.
