Skip to content
Sharp

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
java
private List<Order> orders;

public List<Order> getOrders() {
    return new ArrayList<>(orders);
}
Choose one answer
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.

Start free test
All Object-oriented programming questions →