There are couple of useful factory methods introduced in Java 9 to create immutable (unmodifiable) lists.
1. Creating immutable list prior to Java 9
Before we see the factory methods that are introduced in Java 9. Lets see how we used to create immutable lists prior to Java 9.
1.1 Creating empty immutable list before java SE 9
Prior to Java 9, we have to use unmodifiableList() method of Collections class to create immutable list.
List<String> noElementList = new ArrayList<String>(); List<String> immuList = Collections.unmodifiableList(noElementList);
Note: Lets test the code in Java Shell (JShell).
1.2 Creating Non-empty immutable list before Java SE 9
List<String> list = new ArrayList<String>(); list.add("Chaitanya"); list.add("Rick"); list.add("Glenn"); List<String> immuList = Collections.unmodifiableList(list);
2. Java 9 – Creating Immutable list using static factory method of()
Java 9 introduced couple of versions of of() method to create unmodifiable lists.
static <E> List<E> of()
2.1 Java 9 – Creating empty immutable list
List<String> immuList = List.of();
2.2 Java 9 – Creating Non-empty immutable list
Lets take the same example that we have taken above using the unmodifiableList() method. As you can see how simple it is to create such lists in Java 9. We have reduced the 5 lines of code to a single line using factory method of().
List<String> immuList = List.of("Chaitanya", "Rick", "Glenn");
What is an immutable List?
1. An immutable list doesn’t allow the add, delete and update of its elements.
jshell> List<String> immuList = List.of("Chaitanya", "Rick", "Glenn"); immuList ==> [Chaitanya, Rick, Glenn] jshell> immuList.add("Negan") | java.lang.UnsupportedOperationException thrown: | at ImmutableCollections.uoe (ImmutableCollections.java:71) | at ImmutableCollections$AbstractImmutableList.add (ImmutableCollections.java:77) | at (#2:1)
2. We can’t add null elements to an immutable list.
jshell> List<String> immuList = List.of("Chaitanya", "Rick", "Glenn"); immuList ==> [Chaitanya, Rick, Glenn] jshell> immuList.add(null) | java.lang.UnsupportedOperationException thrown: | at ImmutableCollections.uoe (ImmutableCollections.java:71) | at ImmutableCollections$AbstractImmutableList.add (ImmutableCollections.java:77) | at (#2:1)
Leave a Reply