If after creating an unmodifiable list instance, you cannot add, remove or replace# from the list ## element, the list is considered an unmodifiable list. Static factory method: List.of() Provides a convenient way to create unmodifiable lists in Java 9.
The list instance created using theList.of() method has the following characteristics.
<strong>List.of(E... elements)</strong>
import java.util.List; public class UnmodifiedListTest { public static void main(String[] args) { <strong> List<String></strong> countries = <strong>List.of</strong>("India", "Australia", "England", "Newzealand"); System.out.println("Countries - " + countries); countries.add("Srilanka"); <strong>// throws UnsupportedOperationException</strong> } }
<strong>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)</strong>
The above is the detailed content of In Java 9, how can we create an immutable list?. For more information, please follow other related articles on the PHP Chinese website!