Sobes.tech
Junior — Middle

How can you create a class whose objects cannot be modified after initialization, while it contains a collection as one of its components?

sobes.tech AI

Answer from AI

To create an immutable class with a collection in Java, you need to:

  1. Declare the class as final so it cannot be subclassed and its behavior cannot be changed.
  2. Make all fields private and final.
  3. Initialize the collection in the constructor by creating a copy (for example, using new ArrayList<>(...)) so external modifications do not affect the internal state.
  4. Return from getters either unmodifiable wrappers over collections (Collections.unmodifiableList(...)) or copies of collections to prevent external modification.

Example:

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

public final class ImmutableClass {
    private final List<String> items;

    public ImmutableClass(List<String> items) {
        // Create a copy of the collection to protect against external modifications
        this.items = Collections.unmodifiableList(List.copyOf(items));
    }

    public List<String> getItems() {
        return items; // return an unmodifiable list
    }
}

Thus, after creating the object, its collection cannot be changed.