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:
- Declare the class as
finalor not provide methods for inheritance. - Make all fields
private final. - Do not provide setters.
- 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.