Sobes.tech
Junior

What are immutable objects?

sobes.tech AI

Answer from AI

Objects whose state cannot be changed after creation. When modification is attempted, a new object is always created.

Examples of immutable classes in Java:

  • String
  • Primitive wrappers (Integer, Long, Boolean, etc.)
  • Some collections (Collections.unmodifiableList(), ImmutableList from Guava)

Advantages:

  • Thread safety (do not require synchronization when accessed concurrently).
  • Easy to use (easy to understand the state of the object).
  • Can be used as keys in HashMap or elements in Set (their hash code and equals() do not change).
  • Improve performance through caching and reuse.

Disadvantages:

  • Creating a new object for each modification can be inefficient for frequent changes.

Creating your own:

  • Declare the class final.
  • Make all fields private and final.
  • Do not provide setter methods.
  • In getters for mutable fields, return copies rather than references to the original objects.
public final class ImmutablePerson {
    private final String name;
    private final int age;
    private final List<String> hobbies;

    public ImmutablePerson(String name, int age, List<String> hobbies) {
        this.name = name;
        this.age = age;
        // Create a copy to prevent external modification
        this.hobbies = new ArrayList<>(hobbies);
    }

    public String getName() {
        return name;
    }

    public int getAge() {
        return age;
    }

    public List<String> getHobbies() {
        // Return an unmodifiable wrapper
        return Collections.unmodifiableList(hobbies);
    }
}