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.
- Factory method to create Immutable Set in Java 9
- Factory method to create immutable Map in Java 9
- How to create Immutable class in Java?
- Immutable List in Java
- Immutable Map in Java
- Immutable Set in Java
- Java: String is Immutable. What exactly is the meaning?
- Primitive Wrapper Classes are Immutable in Java
- List add() Method in Java with Examples
- List add(E ele) method in Java with Examples
- List contains() method in Java with Examples
- List get() method in Java with Examples
- Collections list() method in Java with Examples
- List hashCode() Method in Java with Examples
- List retainAll() Method in Java with Examples