My Array is this:
int[][] arr = new int[3][4];
I want to dismiss the changes happens to my array in the function. How can pass it to a function by value?
Thank you.
My Array is this:
int[][] arr = new int[3][4];
I want to dismiss the changes happens to my array in the function. How can pass it to a function by value?
Thank you.
You can't pass the array by value.
The only way to keep the original array unchanged is to pass a copy of the array to your method. Note that for a multi-dimensional array you can't use Arrays.copyOf
to create that copy, since it performs shallow copy, so the internal arrays won't be duplicated (their references will be copied).
public static int[][] cloneArray(int[][] src) {
int length = src.length;
int[][] target = new int[length][src[0].length];
for (int i = 0; i < length; i++) {
System.arraycopy(src[i], 0, target[i], 0, src[i].length);
}
return target;
}
In Java you cannot pass an array (or any Object
, for that matter) by value. References to Object
s are passed by value, giving the method being called full access to the data inside the object.
In order to fix this problem, do one of the following: