Java 9引入了工厂方法来使用List.of创建不可变列表.
哪个更适合创建一个元素的不可变列表?
List<String> immutableList1 = List.of("one");
List<String> immutableList2 = Collections.singletonList("one");
最佳答案
首选使用工厂方法
List<String> immutableList1 = List.of("one");
因为它们不允许使用null元素,所以它是好处之一,并且List接口中的工厂方法也很容易添加多个对象并创建不可变的List
They disallow null elements. Attempts to create them with null elements result in NullPointerException.
其中Collections.singletonList允许为空值
List<String> l = Collections.singletonList(null);
System.out.println(l); //[null]
本文探讨了在Java9中创建不可变列表的最佳实践。通过比较List.of()和Collections.singletonList(),文章指出List.of()是更优的选择,因为它不允许null元素,并且提供了更简便的方法来创建包含多个对象的不可变列表。
1万+

被折叠的 条评论
为什么被折叠?



