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");
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]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With