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:
- Declare the class as
finalto prevent inheritance and behavior modification. - Make all fields
privateandfinal. - Do not provide setters for the fields.
- For the
Listfield, use an unmodifiable collection or return a copy of the list in getters so that external code cannot modify the internal state. - 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.