Luke
Luke

Reputation: 130

How to link 2 final arrays

So I'm having trouble finding out how to link 2 final arrays. Something like this:

    final String[] array1 = new String[4];
    final String[] array2 = new String[4];

    array1 = array2;

But because both arrays are final, I can't do what I've done in the example above. Is there any way I can set array1 to array2, so that any changes made to array1 will be reflected into array2 automatically?

Thanks in advance.

Upvotes: 0

Views: 43

Answers (2)

Darshan Mehta
Darshan Mehta

Reputation: 30849

If we want the changes of array1 reflected in array2 then we don't need to declare two different arrays. We can just point array2's reference to array1 and it will show the changes e.g.:

final String[] array1 = new String[4];
final String[] array2 = array1;

Upvotes: 1

Konstantin Yovkov
Konstantin Yovkov

Reputation: 62884

Is there any way I can set array1 to array2, so that any changes made to array1 will be reflected into array2 automatically?

Automatically, not. Once you've initialized array1 and array2 with something, you can't re-initialize them again, since they're both final.

However, you could manually copy array2's content to array1.

for (int i = 0; i < 4; i++) {
    array1[i] = array2[i];
}

This will work, because the final modified doesn't guarantee immutability - it just makes sure that once the reference to a variable is set, it cannot change anymore.

Upvotes: 1

Related Questions