java runtime_error ai_generated true

java.lang.UnsupportedOperationException:null(或带有消息:ImmutableList不支持修改)

java.lang.UnsupportedOperationException: null (or with message: ImmutableList does not support modification)

ID: java/unsupportedoperationexception-immutable-list

其他格式: JSON · Markdown 中文 · English
95%修复率
90%置信度
1证据数
2023-03-05首次发现

版本兼容性

版本状态引入弃用备注
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().

generic

官方文档

https://docs.oracle.com/en/java/javase/17/docs/api/java.base/java/lang/UnsupportedOperationException.html

解决方案

  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));`

无效尝试

常见但无效的做法:

  1. 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.

  2. 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.

  3. Casting the list to ArrayList and modifying it 90% 失败

    The underlying object is not an ArrayList; casting will throw ClassCastException.