Using List.of for immutable list with single element instead of Collections.singletonList

佐手、 提交于 2019-12-30 10:28:10

问题


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

回答1:


Prefer using factory method

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

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

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

Where Collections.singletonList allows null value

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


来源:https://stackoverflow.com/questions/55418248/using-list-of-for-immutable-list-with-single-element-instead-of-collections-sing

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!