0

So I have a one-dimensional boolean array representing a two-dimensional shape. It's numbered from 0-8, representing a 3x3 square with this index:

012
345
678

I wrote a function to rotate the shape clockwise using the following code:

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];

Now, when the input of the function is:

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

The expected output would be:

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

However, I instead get:

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

This is not only the result of newShape, but also the result of oldShape, even though I never change oldShape. It would seem that the assignments are changing around references to variables, but not their actual values. How can I fix this?

2
  • 4
    How is newShape declared? How is oldShape declared? What are you passing in and out of your method? Adding some actual code to your question would make it much clearer. Ideally you could even include an MCVE. Commented Jan 16, 2016 at 20:10
  • If the newShape and oldShape array references point to the same array, assigning values to array elements in newShape will still overwrite oldShape array elements, because, they are essentially referencing the same array. Commented Jan 16, 2016 at 20:17

1 Answer 1

2

It seems that you're using the same reference to both newShape and oldShape. You should use different arrays of course. I was able to repoduce your results. Just clone the array

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();
    }
}
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.