I have String array like this one:
String[][][][][] map = new String[9][13][2][1][1];
and when I’m trying update one fild, like this:
map[0][0][1][0][1] = "true";
every fild is updating to “true”, this one:
map[0][1][1][0][1]
this one:
map[0][2][1][0][1]
why this is happening?
this is my code:
int UP = 0;
int UP_RIGHT = 1;
int RIGHT = 2;
int DOWN_RIGHT = 3;
int DOWN = 4;
int DOWN_LEFT = 5;
int LEFT = 6;
int LEFT_UP = 7;
String[][][][][] map = new String[9][13][2][1][1];
public PitchMoveHelper() {
String[][] move = {
{String.valueOf(UP), "false"},
{String.valueOf(UP_RIGHT), "false"},
{String.valueOf(RIGHT), "false"},
{String.valueOf(DOWN_RIGHT), "false"},
{String.valueOf(DOWN), "false"},
{String.valueOf(DOWN_LEFT), "false"},
{String.valueOf(LEFT), "false"},
{String.valueOf(LEFT_UP), "false"}
};
String[][] used = {{"used", "false"}};
for(int z = 0; z < 9; z++) {
for(int x = 0; x < 13; x++) {
map[z][x][0] = used;
map[z][x][1] = move;
}
}
//this.updateLeftBand();
//this.updateRightBand();
//this.updateTopBand();
//this.updateBottomBand();
map[0][0][1][0][1] = "true";
System.out.println(Arrays.deepToString(getPitchMap()));
}
Your immediate problem is that the
Stringarray stores references, not actual strings. When you sayThere is a single instance of
usedbeing referenced by ALL elements[z][x][0]ofmap(and the same formoveand[z][x][1]. Any change indexed by the 4th of 5th subscript is changing that single instance, affecting what is seen by all subscripts.To clarify more, all the following entries in
mappoint to the same instance:To solve the problem you need to make a deep copy of
usedandmovefor every assignment in the loop:Where
deepCopy()makes a complete copy of the input array.