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]