# java.lang.UnsupportedOperationException：null（或带有消息：ImmutableList不支持修改）

- **ID:** `java/unsupportedoperationexception-immutable-list`
- **领域:** java
- **类别:** runtime_error
- **验证级别:** ai_generated
- **修复率:** 95%

## 根因

当尝试通过调用add()、remove()或set()等方法修改不可变集合（例如List.of()、Collections.unmodifiableList()或Guava的ImmutableList）时发生。

## 版本兼容性

| 版本 | 状态 | 引入 | 弃用 |
|------|------|------|------|
| Java 9 | active | — | — |
| Java 11 | active | — | — |
| Java 17 | active | — | — |
| Java 21 | active | — | — |
| Guava 31.x | active | — | — |

## 解决方案

1. ```
   Create a mutable copy of the immutable list before modification: `List<String> mutableList = new ArrayList<>(immutableList); mutableList.add("new element");`
   ```
2. ```
   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.
   ```
3. ```
   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** — The collection remains unmodified; ignoring the exception does not achieve the intended mutation and may lead to data inconsistencies. (80% 失败率)
- **Using Arrays.asList() instead of List.of() but still calling add()** — Arrays.asList() returns a fixed-size list backed by the array; add() still throws UnsupportedOperationException because the size is fixed. (70% 失败率)
- **Casting the list to ArrayList and modifying it** — The underlying object is not an ArrayList; casting will throw ClassCastException. (90% 失败率)
