Senior
How to protect against mutation through getter (returning a copy of the list)?
sobes.tech AI
Answer from AI
To protect against mutation of the internal list through a getter, return not the list itself, but its copy. This prevents external modification of the original list.
Example in Java:
public class MyClass {
private final List<String> items = new ArrayList<>();
public List<String> getItems() {
return new ArrayList<>(items); // return a copy
}
// methods to modify items inside the class
}
Thus, if someone calls getItems() and tries to modify the returned list, the original items will remain unchanged.
Alternatively, you can return an unmodifiable list:
import java.util.Collections;
public List<String> getItems() {
return Collections.unmodifiableList(items);
}
This allows reading the data, but any modification attempt will throw an exception.