java.lang.UnsupportedOperationException:null(或带有消息:ImmutableList不支持修改)
java.lang.UnsupportedOperationException: null (or with message: ImmutableList does not support modification)
ID: java/unsupportedoperationexception-immutable-list
版本兼容性
| 版本 | 状态 | 引入 | 弃用 | 备注 |
|---|---|---|---|---|
| Java 9 | active | — | — | — |
| Java 11 | active | — | — | — |
| Java 17 | active | — | — | — |
| Java 21 | active | — | — | — |
| Guava 31.x | active | — | — | — |
根因分析
当尝试通过调用add()、remove()或set()等方法修改不可变集合(例如List.of()、Collections.unmodifiableList()或Guava的ImmutableList)时发生。
English
This error occurs when an attempt is made to modify an immutable collection (e.g., List.of(), Collections.unmodifiableList(), or Guava's ImmutableList) by calling methods like add(), remove(), or set().
官方文档
https://docs.oracle.com/en/java/javase/17/docs/api/java.base/java/lang/UnsupportedOperationException.html解决方案
-
Create a mutable copy of the immutable list before modification: `List<String> mutableList = new ArrayList<>(immutableList); mutableList.add("new element");` -
Use the builder pattern for mutable collections from the start: `List<String> list = new ArrayList<>(List.of("a", "b"));` or use `Stream.collect(Collectors.toList())` which returns a mutable list. -
For Guava ImmutableList, use the copyOf() method to create a mutable ArrayList: `List<String> mutableList = new ArrayList<>(ImmutableList.copyOf(originalList));`
无效尝试
常见但无效的做法:
-
Catching the exception and ignoring it
80% 失败
The collection remains unmodified; ignoring the exception does not achieve the intended mutation and may lead to data inconsistencies.
-
Using Arrays.asList() instead of List.of() but still calling add()
70% 失败
Arrays.asList() returns a fixed-size list backed by the array; add() still throws UnsupportedOperationException because the size is fixed.
-
Casting the list to ArrayList and modifying it
90% 失败
The underlying object is not an ArrayList; casting will throw ClassCastException.