'What happens when I assign an array argument to a member in constructor?
I have a class MyClass with member float[] myArray. I construct using the following:
public MyClass(float[] initArray) {
myArray = initArray;
}
I'm wondering what happens under the hood: does the JVM set the pointers the same? Am I at any risk of losing the myArray variable to the garbage collector?
Would it be preferable to do the following:
public MyClass(float[] initArray) {
int len = initArray.length;
myArray = new float[len];
System.arraycopy(initArray, 0, myArray, 0, len);
initArray = null;
}
I ask because I am programming on an embedded environment where memory is tight, and I don't want to lose variables (e.g. the first example) or waste extra space (e.g. by setting initArray to null, I want the GC to take care of it and give me back that RAM).
Edit
In the first method, what happens if initArray is a local variable created in some other function?
Solution 1:[1]
Does the JVM set the pointers the same?
Yes.
Am I at any risk of losing the myArray variable to the garbage collector?
No.
As long as you don't modify your array using the initArray reference after the method call, there is no reason to make a copy of your array.
What happens if initArray is a local variable created in some other function?
That is just fine. As long as at least one variable points to your array (in this case, you have your myArray), it won't be eligible for garbage collection.
Solution 2:[2]
The pointer does point to the same array, and as long as it is pointing to the array, it will not be considered as garbage.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Keppil |
| Solution 2 | Anton |
