Java array variables are reference types.
I think it's a natural basic thing, but since I was originally doing PHP, For my own memorandum, I summarized it a little.
For example, in the case of the following code, 100 is output.
int[] a = { 1, 2, 3 };
int[] b = a;
b[0] = 100;
System.out.println(a[0]);
// a[0]Outputs 100.
This is because Java array variables are reference types, so an array was created for int [] a Because the memory address is stored.
For example, if the memory address of the array created by int [] a is ABC123 (I don't think there is actually such a memory address), The array a is recorded at this memory address (location) called ABC123.
And since ABC123, which is the memory address of the array variable int [] a, is contained in int [] b, the point is that it is the same array. Therefore, b [0] = 100 is the same as a [0] = 100.
If you write the same code below in PHP, 1 will be output instead of 100.
$a = [1,2,3];
$b = $a;
$b[0] = 100;
echo $a[0];
//1 is output
This is not a reference type in PHP, it is passed by value, so This is because the array of \ $ a itself is copied and passed to \ $ b, not the memory address of \ $ a.
In PHP, in order to make it a reference type, it is necessary to add \ & as shown below.
$a = [1,2,3];
$b = &$a;
// ↑$Before a&Put on
$b[0] = 100;
echo $a[0];
//100 is output
By doing this, it becomes a reference type, and \ $ b contains the memory address of the array created by \ $ a. Since it is stored, the operation is the same as in the case of Java above.
Recommended Posts