将List.of用于具有单个元素而不是Collections.singletonList的不可变列表 [英] Using List.of for immutable list with single element instead of Collections.singletonList

查看:76
本文介绍了将List.of用于具有单个元素而不是Collections.singletonList的不可变列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

Java 9 introduce factory methods to create immutable lists with List.of.

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

Which is more suitable to create an immutable list of one element ?

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

推荐答案

首选使用工厂方法

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

因为,它们不允许使用null元素是其中的好处之一,并且List界面中的工厂方法很容易添加多个对象并创建不可变的列表

Because they disallow null elements is one of the benefit and also factory methods in List interface are handy to add multiple objects and creates immutable List

它们不允许使用null元素.尝试使用null元素创建它们会导致NullPointerException.

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]

这篇关于将List.of用于具有单个元素而不是Collections.singletonList的不可变列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆