Search code examples
javaarraysencapsulationgetter

How to encapsulate an array in Java


I'm starting with Java and I'm learning about setters, getters and encapsulation. I have a very simple program, two classes:

  • Container has a private int array (numArray) with his setter & getter.

  • Main creates a Container object and uses it in totalArray method.


public class Container {
    private int numArray[]= {0,0,0};
    public int[] getNumArray() {
        return numArray;
    }
    public void setNumArray(int index, int value){
        numArray[index] = value;
    }    
}

public class Main {
    public static void main(String[] args) {
        Container conte = new Container();
        System.out.println(totalArray(conte.getNumArray()));
        conte.getNumArray()[2]++;
        System.out.println(totalArray(conte.getNumArray()));
    }
    private static int totalArray (int v[]){
        int total=0;
        for (int conta =0; conta<v.length;conta++){
            total+=v[conta];
        }
        return total;
    }
}

Problem: I can change the private int array through the getter, I know that's because getNumArray returns a reference to numArray, not the array itself. If I were interested in a single element of the array, I'd make a getter with an index value, but I want the whole array for the totalArray method.

How can I prevent numArray from being modified out of his class?


Solution

  • All you can do to prevent people from changing your array is to provide a copy of it in the getter.

    public int[] getArray() {
        return Arrays.copyOf(numArray, numArray.length);
    }
    

    This way, other methods can change their own copy of the array, but when they call the getter again, they get the original version, unchanged. Only the setNumArray() you provide can actually modify your internal array.

    Otherwise, if you want to completely block the container, you have to drop arrays and use an immutable object. Some libraries provide immutable lists, or use Collections.unmodifiableList.