Getters and setters for arrays

Viewed 77668

I have a few questions about getters and setters for arrays. Suppose we have a class like this, which makes a private copy of an array in its constructor:

import java.util.Arrays;

public class Foo
{
    private int[] array;

    public Foo(int[] array) {
        this.array = Arrays.copyOf(array, array.length);
    }
}

We want the array to only be accessed/mutated via the getters and setters. If we have a getter that looks like this:

public int[] getArray() {
    return array;
}

it defeats the purpose of the getter as we're returning a reference that allows the user to directly modify the elements of the array. e.g.

Foo foo = new Foo(someArray);
...
int[] bar = foo.getArray();
bar[0] = 123; // Now foo.array[0] = 123 and we haven't used a setter!

So presumably we need something like this:

public int getElement(int index) {
    return array[index];
}

Similarly for setters. But if we're doing things on a per-element basis, we're also going to need to provide a means of getting the length:

public int getArrayLength() {
    return array.length;
}

This is already a little messy for a 1-dimensional array, but say we have a multidimensional array instead:

import java.util.Arrays;

public class Foo
{
    private int[][][] array;

    public Foo(int[][][] array) {
        // Code for making a deep copy here
    }

    public int getElement(int i, int j, int k) {
        return array[i][j][k];
    }

    public void setElement(int i, int j, int k, int value) {
        array[i][j][k] = value;
    }

    public int getArrayLength() {
        return array.length;
    }

    public int getArrayLength(int i) {
        return array[i].length;
    }

    public int getArrayLength(int i, int j) {
        return array[i][j].length;
    }
}

This is a lot of code for such a trivial task, and more importantly it's a mess to actually use. Do we really have to end up with something like this, or is there a better way to do it? I've looked all over the place and there doesn't seem to be a "standard practice" for this.

4 Answers
Related