0

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.

Luke
  • 130
  • 1
  • 9

2 Answers2

1

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.

Konstantin Yovkov
  • 62,134
  • 8
  • 100
  • 147
  • What I was trying to do was more complex than my example, I was just trying to show what I was trying to do but thanks to the help of you all I've managed to understand what I'm doing wrong now. Thanks again! – Luke Mar 01 '16 at 10:54
1

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;
Darshan Mehta
  • 30,102
  • 11
  • 68
  • 102