getter和setter方法阵列 [英] Getters and setters for arrays
问题描述
我对getter和setter方法阵列的几个问题。假设我们有这样的一类,这使得数组的拷贝在其构造:
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);
}
}
我们希望才可以访问/通过getter和setter突变的数组。如果我们有一个getter,看起来像这样:
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!
所以presumably我们需要的是这样的:
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;
}
}
这是这样一个简单的任务很多code,而且更重要的是它是一个烂摊子实际使用。难道我们真的有这样的事情结束了,还是有更好的方式来做到这一点?我看了所有的地方和似乎没有成为一个标准做法这一点。
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.
推荐答案
一个多维数组也是一维数组: INT [A] [B] [C]
真的只是 INT [A * b * C]
,所以这个问题归结到,你如何提供安全的访问?只要是这样的:
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);
}
}
这就是它。
呼叫者在阵列的安全拷贝,用于在全正常的方式阵列可以使用它。无需委托方法。
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.
这篇关于getter和setter方法阵列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!