Sobes.tech
Junior — Middle+

How to convert a regular class into an immutable object

livecode

Task condition

It is required to modify this class so that its instances become completely immutable. To do this:

  • remove all setters;
  • declare fields as final;
  • when passing mutable objects (e.g., lists), create their copies to prevent external modifications from affecting internal state;
  • ensure safe access to fields through only getters.

Below is the original code that needs to be adapted to the immutability requirements. You may rename variables, but the structure and logic should remain the same.

public class Element {

    private final int number;
    private final List<String> items;

    public Element(int number, List<String> items) {
        this.number = number;
        // create a copy of the list to prevent external modifications
        this.items = new ArrayList<>(items);
    }

    public int getNumber() {
        return number;
    }

    public List<String> getItems() {
        // return an unmodifiable view of the list
        return Collections.unmodifiableList(items);
    }
}

After these changes, Element objects will be guaranteed immutable: their state cannot be changed after creation, and any attempts to modify the internal list will result in an UnsupportedOperationException.