I want to make the following class immutable, even though it has a mutable List member. How can I achieve this?
class MyImmutableClass {
private List<Integer> data;
public MyImmutableClass(List<Integer> data) {
this.data = data;
}
public List<Integer> getData() {
return data;
}
}
Below is test class whose main()
function that modifies object state.
class TestMyImmutableClass{
public static void main(String[] args) {
List<Integer> data = new ArrayList<Integer>();
data.add(2);
data.add(5);
MyImmutableClass obj = new MyImmutableClass(data);
obj.getData().add(3);
System.out.println("Data is; " + obj.getData());
}
}
O/P : Data is; [2, 5, 3]
In you getData
method, instead of returning a reference to your List
like...
public List<Integer> getData() {
return data;
}
You could return an unmodifiable List
instead
public List<Integer> getData() {
return Collections.unmodifiableList(data);
}
See Collections.unmodifiableList
for more details...
Updated
As pointed out by user949300, you should also make a copy of the original list.
public MyImmutableClass(List<Integer> data) {
this.data = new ArrayList<Integer>(data);
}
This will prevent any one who has access to the original list from making modifications to it.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With