CoderTheTyler
CoderTheTyler

Reputation: 869

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.

Upvotes: 5

Views: 924

Answers (4)

user1512399
user1512399

Reputation:

The second line in the first code example is creating a reference variable of type String [] that refers to the same two-dimensional array object that the reference array1 refers to. There is only one two-dimensional array in memory, but two reference variables refer to it, array1 and array2.

You seem confused about the definition of recursion, so I will point you here- Recursion in Computer Science.

Upvotes: 1

Sergey Kalinichenko
Sergey Kalinichenko

Reputation: 726569

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).

Upvotes: 12

Saurabh Sharma
Saurabh Sharma

Reputation: 2341

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 &

Upvotes: 1

pb2q
pb2q

Reputation: 59617

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]);

Upvotes: 5

Related Questions