Java数组传递引用而不是值

时间:2016-01-16 20:05:07

标签: java arrays

所以我有一个表示二维形状的一维布尔数组。它的编号从0到8,表示该索引的3x3平方:

012
345
678

我写了一个函数,使用以下代码顺时针旋转形状:

newShape[2]=oldShape[0];
newShape[5]=oldShape[1];
newShape[8]=oldShape[2];
newShape[1]=oldShape[3];
newShape[4]=oldShape[4];
newShape[7]=oldShape[5];
newShape[0]=oldShape[6];
newShape[3]=oldShape[7];
newShape[6]=oldShape[8];

现在,当函数的输入为:

false-true-false
true--true-false
false-false-false

预期输出为:

false-true-false
false-true--true
false-false-false

然而,我反而得到:

false-true-false
true--true--true
false-true-false

这不仅是newShape的结果,而且 oldShape的结果,即使我从未改变oldShape。似乎分配正在围绕变量的引用而改变,而不是它们的实际值。我该如何解决这个问题?

1 个答案:

答案 0 :(得分:2)

您似乎对newShape和oldShape使用相同的引用。你当然应该使用不同的数组。我能够重新制作你的结果。只需克隆数组

public class Class {
    public static void main(String[] args) {
        boolean[] oldShape = new boolean[]{
                false, true, false,
                true, true, false,
                false, false, false
        };

        // THIS DOENS TWORK
        boolean[] newShape = oldShape;

        //THIS WILL WORK
//        boolean[] newShape = new boolean[9];

        output(oldShape);

        newShape[2] = oldShape[0];
        newShape[5] = oldShape[1];
        newShape[8] = oldShape[2];
        newShape[1] = oldShape[3];
        newShape[4] = oldShape[4];
        newShape[7] = oldShape[5];
        newShape[0] = oldShape[6];
        newShape[3] = oldShape[7];
        newShape[6] = oldShape[8];

        output(newShape);
    }

    private static void output(boolean[] s) {
        for (int i = 0; i < 3; ++i) {
            for (int j = 0; j < 3; ++j) {
                System.out.print(s[i*3+j] + " ");
            }
            System.out.println();
        }
        System.out.println();
    }
}