JaVaPG JaVaPG - 4 months ago 10x
Java Question

Java - how to return in a method multidimensional array without aliasing

I'm aware that arrays are objects and in java objects are transfered by reference which could cause aliasing so objects should be returned with in this form to not cause aliasing:

return new (object(parameters));

So this is what I'm trying to do with multidimensional arrays, however for some reason compiler says I have an error : "array dimension missing".

public int[][] Testing(int[][]arr)
int[][]newArr=new int[arr.length][arr[0].length];
for(int i=0;i<arr.length;i++)
for(int j=0;j<arr[0].length;j++)
return new int[][]newArr;

Could anyone tell me how to return in a method an multidimensional array without aliasing?

Thank you.


Since you are creating your array inside your method, there is no risk for aliasing in this scenario. Noone else can get a reference to your array.

A simple

return newArr;

will work just fine.