Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I make this class immutable despite having a mutable member?

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]

like image 808
user2745108 Avatar asked Dec 07 '22 05:12

user2745108


1 Answers

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.

like image 67
MadProgrammer Avatar answered Dec 22 '22 01:12

MadProgrammer