Skip to content

docs: clarify List.of immutability in the array-to-list section - #2941

Closed
YangFang1999 wants to merge 2 commits into
Snailclimb:mainfrom
YangFang1999:docs/list-of-immutable
Closed

YangFang1999 wants to merge 2 commits into
Snailclimb:mainfrom
YangFang1999:docs/list-of-immutable

Conversation

@YangFang1999

Copy link
Copy Markdown

Closes #2649

按 #2940 中的方案,澄清「数组转集合」一节中 List.of() 的不可变语义:

小节标题由 ArrayList 改为 List(第 6 种方法返回的是不可变集合,不总是 ArrayList)
方法 6 标题标注「不可变」
补充说明:List.of() 返回 java.util.ImmutableCollections 的实现,add/remove/set 会抛出 UnsupportedOperationException,包含 null 元素会抛出 NullPointerException
补充与 Arrays.asList() 的区别:后者为定长列表,可通过 set 替换元素;List.of() 完全不可变
补充需要可变集合时的写法:new ArrayList<>(List.of(array)) 之后可正常增删
已按 #2940 的验证清单核对:三种修改操作均抛 UnsupportedOperationException,null 元素抛 NullPointerException。

Refs #2940

@Snailclimb

Copy link
Copy Markdown
Owner

感谢补充!这份 PR 与已合并的 #2940 修改了同一个「数组转集合」小节,核心内容已由 #2940 覆盖:

  • 将标题中的 ArrayList 改为 List,避免暗示所有方法都返回 ArrayList。
  • 说明 List.of() 不支持 add()、remove()、set() 等修改操作,也不允许包含 null 元素。
  • 区分它与 Arrays.asList() 的行为,并提供复制到可变 ArrayList 的示例。

因此这里按重复 PR 关闭,不再重复合并。感谢对文档的完善!

@Snailclimb Snailclimb closed this Nov 27, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

关于数组转集合方法的第六种:使用Java9的List.of()

2 participants