Sobes.tech
Senior

What needs to be done with the class (with fields longId and List of objects) to make its objects immutable?

sobes.tech AI

Answer from AI

To make a class with fields longId and a List of objects immutable, you need to:

  1. Declare the class as final to prevent inheritance and behavior modification.
  2. Make all fields private and final.
  3. Do not provide setters for the fields.
  4. For the List field, use an unmodifiable collection or return a copy of the list in getters so that external code cannot modify the internal state.
  5. Initialize all fields through the constructor.

Example:

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

public final class ImmutableClass {
    private final long longId;
    private final List<Object> objects;

    public ImmutableClass(long longId, List<Object> objects) {
        this.longId = longId;
        // Create an unmodifiable copy of the list
        this.objects = Collections.unmodifiableList(List.copyOf(objects));
    }

    public long getLongId() {
        return longId;
    }

    public List<Object> getObjects() {
        return objects;
    }
}

Thus, objects of this class will be immutable after creation.