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.
Invest now in Acorns!!! 🚀
Join Acorns and get your $5 bonus!
Acorns is a micro-investing app that automatically invests your "spare change" from daily purchases into diversified, expert-built portfolios of ETFs. It is designed for beginners, allowing you to start investing with as little as $5. The service automates saving and investing. Disclosure: I may receive a referral bonus.
Invest now!!! Get Free equity stock (US, UK only)!
Use Robinhood app to invest in stocks. It is safe and secure. Use the Referral link to claim your free stock when you sign up!.
The Robinhood app makes it easy to trade stocks, crypto and more.
Webull! Receive free stock by signing up using the link: Webull signup.
More Related questions...
