Java 9 was released around march 2017 and In Java 9 there are some features are added in Java language and factory method for immutable List is one of them.
Characteristics of Immutable List:
- As the name suggest these lists are immutable.
- If any attempt made to add, delete and update elements in the list we will have UnsupportedOperationException.
- Immutable list do not allow null element either.
- If any attempt made to create a immutable list with null element, we will have NullPointerException. If any attempt made to add null element in list, we will have UnsupportedOperationException.
Creating immutable list in Java 8
In Java SE 8, to create immutable list in java 8 we use, java.util.Collections.unmodifiableList(List list) method.unmodifiableList(List list). This method returns an unmodifiable view of the specified list. This method allows modules to provide users with “read-only” access to internal lists.
Syntax: public static List unmodifiableList(List list) Returns: an unmodifiable view of the specified list. Exception: NA
Java code for immutable empty and non-empty list in java 8:
 [contribute.geeksforgeeks.org, www.geeksforgeeks.org]
Now lets try adding elements in the immutable list
Runtime Error : Exception in thread "main" java.lang.UnsupportedOperationException at java.util.Collections$UnmodifiableCollection.add(Collections.java:1055) at ImmutableListDemo.main(File.java:15)
Creating immutable list in Java 9
Java SE 9 has introduced couple of methods in List interface to create immutable list. To create immutable list in Java 9, we use of() method.
Java code for creating immutable list in Java 9:
empty immutable list:  non-empty immutable list: [contribute, ide]
Lets try adding some elements in immutable list:
After running the above code, you must have obtain UnsupportedOperationException.
This article is contributed by Abhishek Verma. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to email@example.com. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
Attention reader! Don’t stop learning now. Get hold of all the important Java Foundation and Collections concepts with the Fundamentals of Java and Java Collections Course at a student-friendly price and become industry ready. To complete your preparation from learning a language to DS Algo and many more, please refer Complete Interview Preparation Course.