In java, the List.of() method is used to create an immutable list.
Once created, it could not be modified.
/** * @author lautturi.com * Java example: */ import java.util.*; public class Lautturi { public static void main(String[] args) { List<String> immuList = List.of("hello","lautturi","java","python","world","lau"); System.out.println(immuList); } }
If we try to add new element to an immutable list,it will throw an UnsupportedOperationException.
immuList.add("php");
Exception message:
Exception in thread "main" java.lang.UnsupportedOperationException at java.base/java.util.ImmutableCollections.uoe(ImmutableCollections.java:142) at java.base/java.util.ImmutableCollections$AbstractImmutableCollection.add(ImmutableCollections.java:147)