gpt4 book ai didi

java - 将 List.of 用于具有单个元素而不是 Collections.singletonList 的不可变列表

转载 作者:塔克拉玛干 更新时间:2023-11-02 19:05:58 25 4
gpt4 key购买 nike

Java 9 引入了工厂方法以使用 List.of 创建不可变列表。

哪个更适合创建一个元素的不可变列表?

    List<String> immutableList1 = List.of("one");
List<String> immutableList2 = Collections.singletonList("one");

最佳答案

更喜欢使用工厂方法

List<String> immutableList1 = List.of("one");

因为它们不允许空元素是好处之一,而且 List 接口(interface)中的工厂方法可以方便地添加多个对象并创建不可变列表

They disallow null elements. Attempts to create them with null elements result in NullPointerException.

Collections.singletonList 允许 null

List<String> l = Collections.singletonList(null);
System.out.println(l); //[null]

关于java - 将 List.of 用于具有单个元素而不是 Collections.singletonList 的不可变列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55418248/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com