How can we create an unmodifiable List in Java 9?

JavaObject Oriented ProgrammingProgramming

A list considered to be unmodifiable if the elements can't be added, removed, or replaced from a list once an unmodifiable instance of a list has created. The static factory method: List.of() provides a convenient way to create unmodifiable lists in Java 9.

An instance of a list created by using the List.of() method has the following characteristics.

  • The list returned by a factory method is conventionally immutable. It means that the elements can't be added, removed, or replaced from a list. Calling any mutator method on the List causes UnsupportedOperationException.
  • If the contained elements of List are mutable, it may cause the List's contents to appear to change.
  • An immutable list can be created using static factory methods that don't allow null elements. If we are trying to create with null elements, it throws NullPointerException.
  • An unmodifiable lists are serializable if all elements are serializable.
  • The order of elements in a list is the same as the order of the provided parameters, or of the elements in the provided array.

Syntax

List.of(E... elements)

Example

import java.util.List;
public class UnmodifiedListTest {
   public static void main(String[] args) {
      List<String> countries = List.of("India", "Australia", "England", "Newzealand");
      System.out.println("Countries - " + countries);
      countries.add("Srilanka"); // throws UnsupportedOperationException
   }
}

Output

Countries - [India, Australia, England, Newzealand]
Exception in thread "main" java.lang.UnsupportedOperationException
 at java.base/java.util.ImmutableCollections.uoe(Unknown Source)
 at java.base/java.util.ImmutableCollections$AbstractImmutableList.add(Unknown Source)
 at UnmodifiedListTest.main(UnmodifiedListTest.java:7)
raja
Published on 19-Feb-2020 12:07:36
Advertisements