Course contentsShow
← Java
Lesson 1246 of 2,87028. Collections Utility ClassFree lesson

When to Use Unmodifiable Collections

Apply unmodifiable collections in API design to expose internal state safely without allowing external mutation.

When to Use Unmodifiable Collections

You'll learn when and why to apply unmodifiable collections to write safer, more maintainable code.

The Core Problem

When you expose a collection directly from your class (like returning a list of items), callers can modify that collection—often by accident—breaking your class's internal consistency. Unmodifiable collections solve this by creating a read-only view that prevents external mutation while allowing safe inspection.

Common Use Cases

1. API Design: Returning Internal State

When your class needs to expose its internal collection, wrap it in an unmodifiable view:

public class Library {
    private List<String> books = new ArrayList<>();
    
    // Safe: callers can read but not modify
    public List<String> getBooks() {
        return Collections.unmodifiableList(books);
    }
}

Without the unmodifiable wrapper, callers could call getBooks().clear() and delete your library's entire collection!

2. Configuration and Constants

When you have fixed, shared data that must never change:

private static final List<String> VALID_STATUSES = 
    Collections.unmodifiableList(Arrays.asList("NEW", "ACTIVE", "CLOSED"));

3. Collaborator Access

When multiple parts of your system need to read data but shouldn't modify it:

public List<Order> getCompletedOrders() {
    return Collections.unmodifiableList(completedOrders);
}

When Not to Use Them

  • When callers legitimately need to modify their own copy (use defensive copying instead)
  • For internal-only collections that never leave your class
  • When performance of creating views becomes a bottleneck (rare)

Key Takeaway: Use unmodifiable collections whenever you expose internal state through public APIs—they prevent accidental mutation while keeping your implementation flexible and your objects' integrity intact.