Search code examples
javaarraysimmutabilitymutability

Why is this class considered mutable?


public class A {
    private int[] values;

    public int[] getValues() {
        return values;
    }
}

A book that I'm reading says that it is not immutable because values is a reference type. I see no way to mutate values other than creating a main method inside of the class.


Solution

  • It is mutable because you can change the contents of values through the method that you exposed

    A obj = new A(...) // values gets filled here
    int[] leak = obj.getValues()
    leak[0] = 42
    

    This would mean that your values property contains now information that has been modified externally. To make it immutable, you should return a copy of the array, so that you are sure no external agent can modify it, and you should make it final, so that no subclasses can be created that can expose the state and make it mutable again:

    public final class A {
      private int[] values;
    
      public int[] getValues() {
        return Arrays.copyOf(values);
      }
    }