Is it possible to return a locally initialized array if not, how can I do this?

Take this example:

public class foo
{
    public int[] func()
    {
        int arr[] = new int[3];
        // here initialised the array

        return arr;
    }
}

I am not familiar with Java, but I know a little C / C ++.

+3
source share
5 answers

Yes, this is completely normal, because garbage collection is performed when there is no further reference to the object. You can also find the size of the array using the lengthinside ( arr.length) or outside (e.g. aFoo.func().length) method.

+6
source

Yes, everything should be fine. Because Java arrays are allocated on the heap not on the stack. They will not be collected after calling the function.

+2
source

Java, ++.

++, [] , ; Java , , .

0
source

It is fine to return a local array, but you must confirm the returned data in the rest of your program so that it continues to serve its purpose.

Relate data to something new.

0
source

This is normal in the C # world.

You can also do this: return new int[] {1,2,3,4};

0
source

Source: https://habr.com/ru/post/1765481/


All Articles