How Can You Create an Immutable List in Java?

How Can You Create an Immutable List in Java?

In Java, an immutable list refers to a list whose elements cannot be modified once the list is created. An immutable list is a common design pattern in Java when you want to create collections that do not change after initialization. This ensures safety in multi-threaded environments and avoids potential errors that might arise from modifying a collection unintentionally.

What is an Immutable List?

An immutable list is a collection in which the elements cannot be added, removed, or modified once the list has been created. Immutable objects are important in programming because they provide thread-safety and predictable behavior. The list can be created using built-in Java methods or libraries like Collections.unmodifiableList() or by leveraging List.of() in Java 9 and later.

When you create an immutable list, the intention is to prevent any alterations. This makes the list useful in scenarios where the collection’s contents must remain constant throughout the lifecycle of an application. The concept is particularly important in functional programming paradigms, where immutability is emphasized.

Why Use Immutable Lists in Java?

There are several reasons why you might use immutable lists in Java:

  • Thread Safety: Immutable objects are inherently thread-safe because they cannot be modified once created. This makes them ideal for concurrent applications.
  • Data Integrity: By preventing modification, immutable lists ensure that their data remains consistent and reliable throughout the program.
  • Security: If a list contains sensitive data, making it immutable ensures that its contents cannot be tampered with.
  • Predictability: Since the list cannot change, its behavior is predictable and avoids errors related to state changes.

Creating an Immutable List in Java

In Java, there are several ways to create an immutable list. Let’s look at some of the most common approaches.

1. Using List.of() in Java 9 and Later

Java 9 introduced the List.of() method, which is a simple way to create immutable lists. This method returns an unmodifiable list, which means you cannot add, remove, or change elements once the list is created.

Here’s an example of using List.of() to create an immutable list:

import java.util.List;

public class ImmutableListExample {
    public static void main(String[] args) {
        // Creating an immutable list using List.of()
        List immutableList = List.of("Apple", "Banana", "Cherry");

        // Attempting to modify the list will throw an UnsupportedOperationException
        // immutableList.add("Orange"); // This line will cause a runtime exception

        System.out.println("Immutable List: " + immutableList);
    }
}

In the example above, List.of() creates an immutable list with three elements: “Apple”, “Banana”, and “Cherry”. Any attempts to modify the list, such as adding or removing elements, will result in an UnsupportedOperationException.

2. Using Collections.unmodifiableList()

If you are working with a version of Java before Java 9, or if you need to create an immutable list from an existing collection, you can use the Collections.unmodifiableList() method. This method returns a read-only view of the original list, meaning the underlying list cannot be modified through the returned object.

import java.util.List;
import java.util.ArrayList;
import java.util.Collections;

public class ImmutableListExample {
    public static void main(String[] args) {
        // Creating a mutable list first
        List mutableList = new ArrayList<>();
        mutableList.add("Apple");
        mutableList.add("Banana");
        mutableList.add("Cherry");

        // Creating an immutable list using Collections.unmodifiableList()
        List immutableList = Collections.unmodifiableList(mutableList);

        // Attempting to modify the list will throw an UnsupportedOperationException
        // immutableList.add("Orange"); // This line will cause a runtime exception

        System.out.println("Immutable List: " + immutableList);
    }
}

In this example, the list is first created as a mutable ArrayList, and then Collections.unmodifiableList() is used to make it immutable. Just like with List.of(), any modification attempts on the returned list will throw an UnsupportedOperationException.

3. Using ImmutableList from Google Guava

Another way to create immutable lists in Java is by using the ImmutableList class from the Google Guava library. Guava is a popular third-party library that provides a lot of utilities, including the creation of immutable collections.

import com.google.common.collect.ImmutableList;

public class ImmutableListExample {
    public static void main(String[] args) {
        // Creating an immutable list using Guava's ImmutableList
        ImmutableList immutableList = ImmutableList.of("Apple", "Banana", "Cherry");

        // Attempting to modify the list will cause an exception
        // immutableList.add("Orange"); // This line will cause a runtime exception

        System.out.println("Immutable List: " + immutableList);
    }
}

Guava’s ImmutableList is immutable by design, meaning it cannot be modified after creation. It is a highly optimized solution for creating immutable collections, and is often preferred in large applications where performance is critical.

Important Considerations

While immutable lists are useful, there are a few things you should consider when working with them:

  • Null Elements: Some methods of creating immutable lists, like List.of(), do not allow null elements. If you try to create a list with null values, it will throw a NullPointerException.
  • Performance: Immutable lists offer thread-safety, but they might incur some performance overhead due to the checks for immutability. Always evaluate whether immutability is a necessity for your specific use case.
  • Nested Collections: Immutable lists do not prevent changes to the objects within them if the objects themselves are mutable. If your list contains mutable objects, make sure the objects themselves are immutable or make defensive copies.

Conclusion

In this article, we explored how to create immutable lists in Java using different methods, including List.of(), Collections.unmodifiableList(), and Google Guava’s ImmutableList. Immutable lists provide thread-safety, data integrity, and security, making them a valuable tool in many Java applications.

Remember, immutability is a key concept in many modern programming paradigms, and understanding how to create and use immutable collections will improve your ability to write clean, safe, and effective Java code.

© 2025 Tech Interview Guide. All Rights Reserved.

Please follow and like us:

Leave a Comment