Sobes.tech
Junior — Middle

How to implement immutability of a user object that contains properties and a collection of nested objects?

sobes.tech AI

Answer from AI

To make a user object in Java immutable, you need to:

  1. Declare the class as final or not provide methods for inheritance.
  2. Make all fields private final.
  3. Do not provide setters.
  4. For collections and nested objects, use immutable structures or create deep copies when passing to the constructor and when returning from getters.

Example:

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

public final class User {
    private final String name;
    private final List<Address> addresses;

    public User(String name, List<Address> addresses) {
        this.name = name;
        // Create an immutable copy of the list
        this.addresses = Collections.unmodifiableList(
            List.copyOf(addresses));
    }

    public String getName() {
        return name;
    }

    public List<Address> getAddresses() {
        return addresses;
    }
}

final class Address {
    private final String city;

    public Address(String city) {
        this.city = city;
    }

    public String getCity() {
        return city;
    }
}

Thus, neither the fields nor nested objects can be modified after the User object is created.

How to implement immutability of a user object that… - sobes.tech