ProgrammingHardProduct-company interview pattern

This class is meant to be immutable. What change is still needed?

This class is meant to be immutable. What change is still needed?
public final class Team {
    private final List<String> members;
    public Team(List<String> m) { members = m; }
    public List<String> getMembers() { return members; }
}
  1. A. Nothing; final class plus private final fields make it immutable
  2. B. Copy the list in the constructor and return an unmodifiable view or copy from the getter
  3. C. Make the getter method final
  4. D. Mark members as static

Correct answer: B. Copy the list in the constructor and return an unmodifiable view or copy from the getter

final stops reassignment of the field, not changes to the list. The caller still holds the list passed in, and getMembers() exposes the internal list, so either side can change it. Defensive copies (e.g. List.copyOf(m)) fix both leaks.

More OOP with C++ and Java questions

Exams that ask this topic