user2397282 user2397282 - 1 month ago 6x
Java Question

Java - array is being changed for no reason

I have this program which takes a 2D array of letters, and scrambles them. However, one line of my code changes a separate array for literally no apparent reason whatsoever?!

Here's the code:

private String[][] words = {{"a", "b", "c"}, {"d", "e", "f"}, {"g", "h", "i"}};

public Scramble()
String[] a = words[2];
// At this point, a = {"g", "h", "i"}
words[2][0] = words[0][2];
// After this line, a changes to {"c", "h", "i"}
words[1][2] = words[2][1];
words[2] = words[1];
words[1] = a;

Why is it doing this?!


Like all Java objects (as opposed to Java primitives), arrays are reference objects. When you do this

String[] a = words[2];

a becomes an alias to words[2]'s content array. Whatever changes you may make to a are happening to words[2] simultaneously and vice versa, because there is only one array object referenced from two places.

When you make this assignment

words[2][0] = words[0][2];

you take a word from [0][2] (i.e. "c") and copy it in place of "g" into the array words[2], which is also the array a. Hence the change of a's content that you observe.

If you do not want a to change when you make changes to words[2], make a copy instead of simply assigning the array:

String[] a = Arrays.copyOf(words[2]);