Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

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");
like image 910
rennajihi Avatar asked Mar 29 '19 13:03

rennajihi


1 Answers

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]
like image 155
Deadpool Avatar answered Nov 14 '22 22:11

Deadpool