Java Guides
With Java 9, new factory methods are added to List, Set and Map interfaces to create immutable instances. These factory methods are convenience factory methods to create a collection in less verbose and in a concise way.
In this post, I show you how to create an immutable list using Java 9 provided List.of() static factory method.
Create Immutable List
Use List.of() static factory methods to create immutable lists. It has following different overloaded versions –
static E> ListE> of() static E> ListE> of(E e1) static E> ListE> of(E e1, E e2) static E> ListE> of(E e1, E e2, E e3) static E> ListE> of(E e1, E e2, E e3, E e4) static E> ListE> of(E e1, E e2, E e3, E e4, E e5) static E> ListE> of(E e1, E e2, E e3, E e4, E e5, E e6) static E> ListE> of(E e1, E e2, E e3, E e4, E e5, E e6, E e7) static E> ListE> of(E e1, E e2, E e3, E e4, E e5, E e6, E e7, E e8) static E> ListE> of(E e1, E e2, E e3, E e4, E e5, E e6, E e7, E e8, E e9) static E> ListE> of(E e1, E e2, E e3, E e4, E e5, E e6, E e7, E e8, E e9, E e10) //varargs static E> ListE> of(E... elements)
- These lists are immutable. Elements cannot be added, removed, or replaced in these lists. Calling any mutator method (i.e. add, addAll, clear, remove, removeAll, replaceAll) will always cause UnsupportedOperationException to be thrown.
- They do not allow null elements. Attempts to add null elements result in NullPointerException.
- They are serializable if all elements are serializable.
- The order of elements in the list is the same as the order of the provided arguments, or of the elements in the provided array.
Create Immutable List Before Java 9 Example
public class ImmutableListExample < public static void main(String[] args) < // Creating an ArrayList of String using List String > fruits = new ArrayList < >(); // Adding new elements to the ArrayList fruits.add("Banana"); fruits.add("Apple"); fruits.add("mango"); fruits.add("orange"); fruits = Collections.unmodifiableList(fruits); // Creating Immutable List //fruits.add("Strawberry"); // Exception in thread "main" // java.lang.UnsupportedOperationException fruits = List.of("Banana", "Apple", "Mango", "Orange"); fruits.forEach(e - > System.out.println(e)); > >
Banana Apple mango orange
Create the Immutable List Example — Java 9 List.of() Method
package net.javaguides.corejava.java9; import java.util.List; /** * Java 9 Immutable List Example * @author Ramesh Fadatare * */ public class ImmutableListExample < public static void main(String[] args) < // Creating Immutable List List String > fruits = List.of("Banana", "Apple", "Mango", "Orange"); fruits.forEach(e - > System.out.println(e)); // You can't add Elements Immutable List // fruits.add("Strawberry"); // Exception in thread "main" java.lang.UnsupportedOperationException // in single list List String > list = List.of("A", "B", "C", "D"); list.forEach(e - > System.out.println(e)); > >
Banana Apple mango orange A B C D
Related Java 9 Posts
- Java 9 Private Methods in Interface with Examples — Learn how to use private methods in interface with examples.
- Java 9 List.of() Method — Create Immutable List Example — In this post, I show you how to create an immutable list using Java 9 provided List.of() static factory method.
- Java 9 Set.of() Method — Create Immutable Set Example — In this post, I show you how to create an immutable Set using Java 9 provided Set.of() static factory method.
- Java 9 Map.ofEntries() Method — Create Immutable Map Example — In this post, I show you how to create an immutable Map using Java 9 provided Map.ofEntries() static factory method.
- Java 9 — Stream API Improvements with Examples — In this article, we will learn what are the Stream API improvements made in Java 9 with an example.
- Java 9 — Optional Class Improvements with Examples — Learn Optional class improvements with examples.
Immutable List in Java
This post will discuss various methods to create an immutable list in Java.
Unmodifiable lists are “read-only” wrappers over other collections. They do not support any modification operations such as add, remove, and clear, but their underlying collection can be changed. Lists that additionally guarantee that no change in the Collection object will ever be visible are referred to as immutable.
When you don’t expect to modify a collection, it’s a good practice to defensively copy it into an immutable collection. Immutable lists have many advantages over their mutable siblings, like they are thread-safe, more memory-efficient, and can be passed to untrusted libraries without any side effects.
The Java Collections framework provides the unmodifiableList() method, but it is unsafe to use as the returned list is only truly immutable if nobody holds a reference to the original collection. The returned list is also inefficient as the data structures will still have all the overhead of mutable collections, including concurrent modification checks, extra space in hash tables, etc.
Guava provides simple, easy-to-use immutable versions of each standard Collection type, including Guava’s own Collection variations. Unlike Collections’ unmodifiableList() , which is a view of a separate collection that can still change, an instance of ImmutableList contains its own private data and will never change.
We can create an ImmutableList collection in several ways:
1. Guava – ImmutableList.copyOf() method
ImmutableList.copyOf() returns an immutable list containing the elements of the specified list. It returns a NullPointerException if any of the elements is null.
Immutable Collections with Factory Methods in Java 9
Learn to create immutable collections such as immutable list, immutable set and immutable map using new factory methods in Java 9.
Table of Contents Create Immutable List Create Immutable Set Create Immutable Map
Use List.of() static factory methods to create immutable lists. It has following different overloaded versions –
static List of() static List of(E e1) static List of(E e1, E e2) static List of(E e1, E e2, E e3) static List of(E e1, E e2, E e3, E e4) static List of(E e1, E e2, E e3, E e4, E e5) static List of(E e1, E e2, E e3, E e4, E e5, E e6) static List of(E e1, E e2, E e3, E e4, E e5, E e6, E e7) static List of(E e1, E e2, E e3, E e4, E e5, E e6, E e7, E e8) static List of(E e1, E e2, E e3, E e4, E e5, E e6, E e7, E e8, E e9) static List of(E e1, E e2, E e3, E e4, E e5, E e6, E e7, E e8, E e9, E e10) //varargs static List of(E. elements)
The List instances created by these methods have the following characteristics:
- These lists are immutable. Elements cannot be added, removed, or replaced in these lists. Calling any mutator method (i.e. add, addAll, clear, remove, removeAll, replaceAll) will always cause UnsupportedOperationException to be thrown.
- They do not allow null elements. Attempts to add null elements result in NullPointerException .
- They are serializable if all elements are serializable.
- The order of elements in the list is the same as the order of the provided arguments, or of the elements in the provided array.
Lets see few examples of usage of immutable list.
package com.howtodoinjava; import java.util.List; public class ImmutableCollections < public static void main(String[] args) < Listnames = List.of("Lokesh", "Amit", "John"); //Preserve the elements order System.out.println(names); //names.add("Brian"); //UnsupportedOperationException occured //java.lang.NullPointerException //List names2 = List.of("Lokesh", "Amit", "John", null); > > Output: [Lokesh, Amit, John]
Set behave very similar to List with only few differences. e.g.
- Set do not allow duplicate elements as well. Any duplicate element passed will result in IllegalArgumentException .
- The iteration order of set elements is unspecified and is subject to change.
All Set factory methods have the same signature as List .
static Set of() static Set of(E e1) static Set of(E e1, E e2) static Set of(E e1, E e2, E e3) static Set of(E e1, E e2, E e3, E e4) static Set of(E e1, E e2, E e3, E e4, E e5) static Set of(E e1, E e2, E e3, E e4, E e5, E e6) static Set of(E e1, E e2, E e3, E e4, E e5, E e6, E e7) static Set of(E e1, E e2, E e3, E e4, E e5, E e6, E e7, E e8) static Set of(E e1, E e2, E e3, E e4, E e5, E e6, E e7, E e8, E e9) static Set of(E e1, E e2, E e3, E e4, E e5, E e6, E e7, E e8, E e9, E e10) //varargs static Set of(E. elements)
Let’s see few examples of immutable sets.
import java.util.Set; public class ImmutableCollections < public static void main(String[] args) < Setnames = Set.of("Lokesh", "Amit", "John"); //Elements order not fixed System.out.println(names); //names.add("Brian"); //UnsupportedOperationException occured //java.lang.NullPointerException //Set names2 = Set.of("Lokesh", "Amit", "John", null); //java.lang.IllegalArgumentException //Set names3 = Set.of("Lokesh", "Amit", "John", "Amit"); > >
Map factory methods are same as List or Set overloaded factory methods. Only difference is that the signatures of the of methods take alternating keys and values as arguments. e.g.
static Map of() static Map of(K k1, V v1) static Map of(K k1, V v1, K k2, V v2) . . static Map ofEntries(Map.Entry. entries)
Java 9 also provide a special method for creating Map entry instance.
static Map.Entry entry(K k, V v)
Let’s take an example of creating immutable Map in java 9.
import java.util.Map; public class ImmutableCollections < public static void main(String[] args) < Mapnames = Map.ofEntries( Map.entry("1", "Lokesh"), Map.entry("2", "Amit"), Map.entry("3", "Brian")); System.out.println(names); //UnsupportedOperationException //names.put("2", "Ravi"); > > Output:
Clearly, new factory methods to create immutable collections in java 9 are very much readable and easy to use.
Drop me your opinion on these immutable collections in comments section.