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).
In the first method, what happens if initArray is a local variable created in some other function?
Does the JVM set the pointers the same?
-> Yes, in Java they are better called references.
Am I at any risk of losing the myArray variable to the garbage collector?
-> No, unless you lose the reference to your MyClass object.
Would it be preferable to do the following?
-> Preferable - no. It depends on what you need,
here you create an actual copy, both are OK.
Setting there the initArray = null; is useless btw
as initArray is not passed in by reference. In Java
everything is passed by value, even references
(initArray is a reference here)
In the first method, what happens if initArray is a
local variable created in some other function?
-> Think of it as you're saving a reference to that local variable
in your MyClass object, you won't lose it when your function finishes
execution (I guess that's your concern). Simply put, it will live
as long as your MyClass object (in which you saved it) lives.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With