开发者

Is it ok to return a locally initialised array, if no how can I do it?

Take this example:

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

        return arr;
    }
}

I'm not expe开发者_开发问答rienced with Java, but I know a little of C/C++.


Yes, it's completely OK, because garbage collection is done when there is no further reference to the object. You can also find the array size by using length inside (arr.length) or outside (e.g. aFoo.func().length) the method.


Yes it should be OK. Because Java arrays are allocated on heap not on stack. They wound't be collected after the function call returns.


Yes in both Java and C++.

The catch is in C++, you will heave to delete[] it manually sometime later to avoid memory leaks; while in Java, the garbage collector will do its thing once there is no more references to the array, so you don't have to do anything.


It is ok to return the local array, but you must substantiate the returned data in the rest of your program so it continues serving a purpose.

Relate the data to something new.


It is perfectly OK in C# world.

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

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜