简体   繁体   中英

Immutable Array with Mutable Objects Java

I have a simple class "A", which is mutable.

I would like to achieve immutable list using mutable objects "A" without creating class that guarantees immutability for objects of type "A". Is this possible?

public class App{
    public class A{
        int a;

        public A() {}

        public A(int a) {
            super();
            this.a = a;
        }

        public int getA() {
            return a;
        }

        public void setA(int a) {
            this.a = a;
        }

        @Override
        public String toString() {
            return "A [a=" + a + "]";
        }

    }

    public static void main( String[] args )
    {
        App app = new App();
        A a = app.new A(0);
        ArrayList<A> aList = new ArrayList<A>();
        aList.add(a);
        System.out.println(aList.toString());//result is 0 as expected
        a.setA(99);
        System.out.println(aList.toString());//result is 99 as expected
        ImmutableList<A> immutableList = ImmutableList.copyOf(new ArrayList<A>(aList));
        System.out.println(immutableList.toString());//result is 99 as expected
        a.setA(50);
        System.out.println(immutable.toString());//result is 50 and I was expecting 99
    }
}

I would probably make A implement an interface ( I ) which exposes the necessary data (via getters) but doesn't expose any mutator methods.

Then, where I needed the immutable list/array, I'd use I rather than A .

This doesn't protect you from nefarious casts or reflection, but then, virtually nothing does.

Note that if you change an object that's in the list not via the list, that change will be visible via the list. So it's not true immutability:

A a = new A(1);
List<I> list = new LinkedList<>();
list.add(a);
System.out.println(list.get(0).getValue()); // 1
a.setValue(2);
System.out.println(list.get(0).getValue()); // 2

For true immutability, you'll have to clone the objects into (say) ImmutableA instances that expose no setters and maintain no backward link to their original object.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM