简体   繁体   中英

Java 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 (eg the first example) or waste extra space (eg 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? Thanks.

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.

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.

指针确实指向同一个数组,只要它指向数组,它就不会被视为垃圾。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM