2

使用java,有没有办法将数组中的某些值设置为静态/不可编辑?我正在尝试制作数独游戏,所以我希望设置初始数字,以便程序无法更改它们,但其他数字可以更改。到目前为止,我已经进行了一些谷歌搜索,但我的搜索都没有找到任何相关信息。

4

1 回答 1

2

您必须通过将其设为私有来隐藏该数组。并且永远不要返回对数组的引用,而是返回一个克隆。

例如

public class ArrayHolder {
    private String[] array;

    public ArrayHolder(String[] inputArray) {
        //make a copy of inputArray
        //assign the reference to the copy to this.array
    }

    public String[] getArray() {
        //make a copy of the array
        //return the reference to the copy
    }
}

至于使某些元素可更新,您必须在类中编写 mutator 方法,以便只有这些方法可以更改数组中的某些元素。

于 2013-02-25T19:20:44.937 回答