Getters and setters for arrays

谁说胖子不能爱 提交于 2019-11-30 18:52:38

A multi-dimensional array is also a 1-dimensional array: int[a][b][c] is really just int[a*b*c], so the problem boils down to, how do you provide access safely? Simply like this:

public class Foo {
    private int[] array;

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

    /** @return a copy of the array */
    public int[] getArray() {
        return Arrays.copyOf(array, array.length);
    }
}

That's it.

Callers have a safe copy of the array and can use it in the full normal way arrays are used. No need for delegator methods.

What do you think ArrayList does, or Vector before it?

I think the better question is why, at this point, are you exposing that Foo is backed by an array at all? If you're trying to encapsulate it, you don't need to have accessors and setters all over the place. If you're just trying to create a class wrapper around the array, then I would suggest you have an interface, call it IntList or something, and make Foo a concrete implementation that's backed by the list.

In relation to the first part could your getter not look like the constructor?

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

I wrote a small API for multidimensional generic arrays. There you have getters, setters for each element, whatever your dimensions are.

MDDAJ on github

Here is a example: creating a 5 dimensional string array:

MDDAPseudo<String> c = new MDDAPseudo<String>(10,20,5,8,15);
c.set("xyz", 0,0,2,1,0); // setter indices: [0][0][2][1][0]
String s = c.get(0,0,0,0,0); // getter indices [0][0][0][0][0]

Bohemian already wrote you can use only one dimension. In this case the class PDDAPSeudo internal have one dimension, too. But the API provides you access like a multi dimensional array

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!