Java array passing reference instead of value -
so have one-dimensional boolean array representing two-dimensional shape. it's numbered 0-8, representing 3x3 square index:
012 345 678
i wrote function rotate shape clockwise using 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 input of function is:
false-true-false true--true-false false-false-false
the expected output be:
false-true-false false-true--true false-false-false
however, instead get:
false-true-false true--true--true false-true-false
this not result of newshape
, also result of oldshape
, though never change oldshape
. seem assignments changing around references variables, not actual values. how can fix this?
it seems you're using same reference both newshape , oldshape. should use different arrays of course. able repoduce results. clone array
public class class { public static void main(string[] args) { boolean[] oldshape = new boolean[]{ false, true, false, true, true, false, false, false, false }; // doens twork boolean[] newshape = oldshape; //this 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) { (int = 0; < 3; ++i) { (int j = 0; j < 3; ++j) { system.out.print(s[i*3+j] + " "); } system.out.println(); } system.out.println(); } }
Comments
Post a Comment