Phase 16 of 20 · Topic 16.5

Collections Utility Methods & Immutable Collections (List.of)

1Concept

Modern Java provides factory methods: `List.of()`, `Set.of()`, `Map.of()` that produce truly unmodifiable, memory-optimized collections that throw `UnsupportedOperationException` on mutation attempts. `Collections` class offers algorithms like `Collections.sort()`, `Collections.binarySearch()`, and `Collections.synchronizedList()`.

2Architecture Diagram

List.of("A", "B"); ---> Compact Immutable Instance (Zero wrapper overhead, no mutations permitted)

3Code Example

Core Java
import java.util.Collections;
import java.util.List;
import java.util.Map;

public class ImmutableCollectionsDemo {
    public static void main(String[] args) {
        // Modern Immutable Collections (Java 9+)
        List<String> immutableList = List.of("PROD", "STAGING", "DEV");
        Map<String, Integer> httpCodes = Map.of("OK", 200, "NOT_FOUND", 404);

        System.out.println("Immutable List Size: " + immutableList.size());
        System.out.println("HTTP OK Code: " + httpCodes.get("OK"));

        try {
            immutableList.add("LOCAL"); // Throws UnsupportedOperationException
        } catch (UnsupportedOperationException e) {
            System.out.println("Mutation Rejected: Immutable Collection Protected!");
        }
    }
}

4Expected Output

Immutable List Size: 3
HTTP OK Code: 200
Mutation Rejected: Immutable Collection Protected!

5Key Takeaways

  • `List.of()`, `Set.of()`, and `Map.of()` reject null elements with NullPointerException.
  • `Set.of()` throws IllegalArgumentException at creation time if duplicate keys are detected.
  • Immutable collections are inherently thread-safe and consume less memory than ArrayList.