Sobes.tech
Junior — Middle

What distinguishes objects declared as Unmodifiable from fully Immutable objects in Java?

sobes.tech AI

Answer from AI

In Java, objects declared as Unmodifiable and fully Immutable objects differ in the level of guarantee of immutability:

  • Unmodifiable objects are objects that do not allow changing their state through the provided interface, for example, through collection methods from Collections.unmodifiableList(). However, if the original object is changed directly, the changes will be visible in the "unmodifiable" view. That is, surface immutability depends on the fact that no one changes the original data.

  • Immutable objects are objects whose state cannot change after creation. All fields are usually final, there are no setters, and internal structures are also immutable. Such objects guarantee complete immutability, which increases safety and simplifies multithreading.

Example of Unmodifiable:

List<String> list = new ArrayList<>();
list.add("a");
List<String> unmodList = Collections.unmodifiableList(list);
list.add("b"); // unmodList will also see "b"

Example of Immutable:

public final class ImmutablePoint {
    private final int x;
    private final int y;

    public ImmutablePoint(int x, int y) {
        this.x = x;
        this.y = y;
    }

    public int getX() { return x; }
    public int getY() { return y; }
}

Thus, immutable objects provide a more strict and deep immutability compared to unmodifiable.