Reputation: 189
So is it possible to reference another array element from within a different array?
Like this
String[] array1 = new String[] {"World"};
String[] array2 = new String[] {"Hello", array1[0]};
array1[0] = "David";
for(String element : array2)
System.out.print(element);
When I try to print the array, it just prints HelloWorld and not HelloDavid
Is this possible? If not, is this possible using variables?
Upvotes: 1
Views: 1335
Reputation: 13066
String[] array2 = new String[] {"Hello", array1[0]};
In above code you are creating an array called array2
whose 0th
index is containing the reference of String literal
"Hello" and 1st
index is containing the reference of String
literal("World") present in StringPool
to which array1[0] is also referencing . According to JLS3.10.5-1
array2[1]
is changed by compiler as follows:
String[] array2 = new String[] {"Hello", "World"};
Now in line :
array1[0] = "David";
You make array[0]
to contain the reference of the String "David" newly created in StringPool
. But it is not going to change the element present at index 1
of array2
. Since array2[1]
is already referring to String literal "World" present in StringPool
.
You would have get "HelloDavid" output if you make following changes in your code:
array1[0] = "David";
array2[1] = array1[0];
Upvotes: 0
Reputation: 7179
What you have is valid, but the output will be HelloWorld
, not HelloDavid
Although array1[0]
will have a new value, array1
will be unaffected as it stores the String value reference, not the array reference, so when the array reference gets updated the Strings referenced in the array are no altered
Edit
Following on from your question what you're looking for is pointer functionality (as provided by C++). The following multi-dimensional solution isn't exactly the same and its pretty clunky, but it would do what you wanted:
String[] array1 = new String[]{"World"};
String[][] array2 = new String[][]{new String[] {"Hello" }, array1};
array1[0] = "David";
for (String[] element : array2)
System.out.print(element[0]);
==> output: HelloDavid
Upvotes: 7