Java / Lombok Interview questions
What are the risks of using @Data with mutable collections?
A field like private List<String> tags; under @Data gets a plain getter
that returns the actual internal list reference, not a defensive copy — meaning external code that calls
the getter can mutate the object's internal state directly, bypassing any invariant the class was supposed to
maintain.
@Data public class Team { private List<String> members; } Team t = new Team(List.of("Ada")); t.getMembers().add("Grace"); // mutates Team's internal state from outside, if the list itself is mutable
This also interacts badly with @EqualsAndHashCode and HashSet/HashMap
usage: if such an object is placed in a hash-based collection and then its internal collection field is
mutated externally (changing its hash code), the object can become "lost" in that collection, unable to be
found by a subsequent lookup even though it's still physically present. Defensive copying in the getter, or
exposing an unmodifiable view, is something you'd have to add manually — Lombok doesn't do it for you.
More Related questions...