Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java: How arrays work

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.

like image 695
CoderTheTyler Avatar asked Aug 13 '12 02:08

CoderTheTyler


3 Answers

No, it is not the same thing: arrays are reference objects, so array2 becomes an alias of array1, not its copy. Any assignment that you make to an element of array2 become "visible" through array1, and vice versa. If you would like to make a copy of a single-dimension array, you can use its clone() 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).

like image 166
Sergey Kalinichenko Avatar answered Oct 24 '22 11:10

Sergey Kalinichenko


array2 = array1 doesn't make copies of the elements, only the array reference. So array2 and array1 both reference the same underlying array.

This is very easy to determine for yourself:

String[][] array1 = new String[4][4];
array1[0][0] = "some string";
String[][] array2 = array1;
array1[0][0] = "another string";
System.out.println("array2: " + array2[0][0]);
array2[0][0] = "a third string";
System.out.println("array1: " + array1[0][0]);
like image 38
pb2q Avatar answered Oct 24 '22 10:10

pb2q


Hmm I think when you make one array equal to another, you simply change the reference. For example:

ARRAY 1 - * [][][][]...[][] where * is a reference to Array 1
Array 2 - & [][][][]...[][] where & is the reference to Array 2

Then Setting Array 1 = Array 2 Array 1 Will simply change its reference to & and start reading at the memory reference &

like image 1
foklepoint Avatar answered Oct 24 '22 11:10

foklepoint