← Back to Chapters

Immutable Collections in Advance Java

? Immutable Collections in Advance Java

? Quick Overview

Immutable Collections are collections whose contents cannot be changed after creation. In Java, immutable collections were officially introduced in Java 9 using factory methods. They improve safety, readability, and performance in modern Java applications.

? Key Concepts

  • Immutable means no add, remove, or update operations allowed
  • Available for List, Set, and Map
  • Thread-safe by design
  • Introduced in Java 9 using of() methods

? Syntax / Theory

Java provides static factory methods to create immutable collections. Once created, any attempt to modify them throws UnsupportedOperationException.

  • List.of(elements)
  • Set.of(elements)
  • Map.of(key, value)

? Code Example(s)

? View Code Example
// Creating an immutable List using Java 9+
import java.util.List;

public class ImmutableListDemo {
public static void main(String[] args) {
List names = List.of("Java", "Python", "C++");
System.out.println(names);
}
}
? View Code Example
// Attempting to modify immutable collection causes exception
import java.util.List;

public class ModifyImmutable {
public static void main(String[] args) {
List nums = List.of(1, 2, 3);
nums.add(4);
}
}

? Interactive Simulation

Try adding elements to see the difference!

ArrayList (Mutable)

  • "Initial"

List.of() (Immutable)

  • "Fixed"
  • "Fixed"
⚠️ java.lang.UnsupportedOperationException

? Live Output / Explanation

Explanation

The first program prints the list successfully. The second program throws UnsupportedOperationException because immutable collections do not allow modification.

✅ Tips & Best Practices

  • Use immutable collections for constants and fixed data
  • Prefer them in multi-threaded environments
  • Avoid null elements — immutable collections do not allow nulls
  • Use mutable collections only when modification is required

? Try It Yourself

  1. Create an immutable Set of colors
  2. Create an immutable Map of roll numbers and names
  3. Try modifying them and observe the exception