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

Rachid Ennaj :

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

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]

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=100829&siteId=1