
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Factory Method to Create Immutable List in Java SE 9
With Java 9, new factory methods are added to List interface to create immutable instances. These factory methods are convenience factory methods to create a collection in less verbose and in concise way.
Old way to create collections
Example
import java.util.ArrayList; import java.util.Collections; import java.util.List; public class Tester { public static void main(String []args) { List<String> list = new ArrayList<>(); list.add("A"); list.add("B"); list.add("C"); List<String> readOnlylist = Collections.unmodifiableList(list); System.out.println(readOnlylist); try { readOnlylist.remove(0); } catch (Exception e) { e.printStackTrace(); } } }
Output
It will print the following output.
[A, B, C] java.lang.UnsupportedOperationException at java.util.Collections$UnmodifiableList.remove(Collections.java:1317) at Tester.main(Tester.java:15)
New Methods
With java 9, following methods are added to List interface along with their overloaded counterparts.
static <E> List<E> of(); // returns immutable list of zero element static <E> List<E> of(E e1); // returns immutable list of one element static <E> List<E> of(E e1, E e2); // returns immutable list of two elements static <E> List<E> of(E e1, E e2, E e3); //... static <E> List<E> of(E e1, E e2, E e3, E e4, E e5, E e6, E e7, E e8, E e9, E e10); static <E> List<E> of(E... elements);// returns immutable list of arbitrary number of elements.
Points to Note
For List interface, of(...) method is overloaded to have 0 to 10 parameters and one with var args parameter.
These methods returns immutable list and elements cannot be added, removed, or replaced. Calling any mutator method will always cause UnsupportedOperationException to be thrown.
New way to create immutable collections
Example
import java.util.ArrayList; import java.util.Collections; import java.util.List; public class Tester { public static void main(String []args) { List<String> list = List.of("A","B","C"); System.out.println(list); try { list.remove(0); } catch (Exception e) { e.printStackTrace(); } } }
Output
It will print the following output.
[A, B, C] java.lang.UnsupportedOperationException at java.util.Collections$UnmodifiableList.remove(Collections.java:1317) at Tester.main(Tester.java:10)
Advertisements