Immutable ArrayList in Java with Example

In this tutorial, we will learn how to make immutable ArrayList with an example.

We will see two examples to make immutable ArrayList:
  • First, we will see how to create an immutable ArrayList using Collections.unmodifiableList() method with an example
  • Second, we will see how to create the Immutable ArrayList with Java 9 List.of() factory method example.

Create Immutable ArrayList with Collections.unmodifiableList() Exmaple

In the following, we create an immutable ArrayList using Collections.unmodifiableList() method with an 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<String> fruits = List.of("Banana", "Apple", "Mango", "Orange");
        fruits.forEach(e - > System.out.println(e));
    }
}
Output:
Banana
Apple
mango
orange

Create the Immutable ArrayList Example - Java 9 List.of() Method

Let's use List.of() static factory methods to create immutable ArrayList.
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));
    }
}
Output:
Banana
Apple
mango
orange
A
B
C
D

Conclusion

In this tutorial, we have seen how to make immutable ArrayList using Collections.unmodifiableList() method and Java 9 List.of() factory method with an example.

Collections Examples

References

Comments