Object-oriented programming · interview question
Given the code snippet below, how can you make the 'orders' list immutable to protect it from external modifications?
Multiple choiceHardchapter-3-curatedpremiumoopdefensive-copying
private List<Order> orders;
public List<Order> getOrders() {
return new ArrayList<>(orders);
}Answer and explanation
Correct answer
C. Return a defensive copy of the list
Why
To protect the 'orders' list, you should return a defensive copy. This ensures that external code cannot modify the internal list, preserving encapsulation.
Test yourself on Object-oriented programming
A free test with instant, explained results. No account needed.
More Object-oriented programming questions
- Why does declaring a method as 'final' in a superclass change runtime behavior?
- Why might a developer choose to use a 'restock' method rather than a public setter for inventory?
- How do unmodifiable views differ from defensive copies in protecting internal collections?
- In an e-commerce application, what is the advantage of using a 'processOrder' method in a Product class?
- Which statement is true about interfaces in Java?
- Why are public mutable fields risky in a store model?