I was working with relatively large String arrays today. (Roughly 400 x 400 in size) I was wondering how making one array equal to another works exactly. For instance,
String[][] array1 = new String[400][400];
String[][] array2 = array1;
Is making one array equal to another the same thing as looping through each element and making it equal to the respective position in another array? (Like below)
for(int y = 0; y < 400; y++) {
for(int x = 0; x < 400; x++) {
array2[x][y] = array1[x][y];
}
}
Now is the looping method the same thing as making one array equal to another? Or is the first/second faster than the other? Personally, I think the first would be faster just because there is no recursion or having to manually allocate memory to array2 before the recursion. But, I have no idea where to start looking for this information and I would like to understand the logistics of how Java processes these kinds of things.
No, it is not the same thing: arrays are reference objects, so
array2becomes an alias ofarray1, not its copy. Any assignment that you make to an element ofarray2become “visible” througharray1, and vice versa. If you would like to make a copy of a single-dimension array, you can use itsclone()method; note that the copy will be shallow, i.e. the individual elements of the array will not be cloned (making the trick inapplicable to the 2-D array that you described in your post).