Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 579
JDS Avatar asked Jan 17 '26 18:01

JDS


1 Answers

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.

like image 196
peter.petrov Avatar answered Jan 19 '26 08:01

peter.petrov



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!