简体   繁体   中英

How to pass a two dimensional array by value in Java?

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:

  • Stop making changes to the original array inside the method. Instead, make a copy explicitly, and work on it.
  • The above approach is fragile, because Java does not enforce the "no change" requirement. Another approach is to encapsulate your array inside an immutable class, and let the class deal with making copies of the array.
  • Finally, you could make a class that gives you a fully encapsulated array, and implements a copy-on-write strategy. This approach lets you make copies when needed, potentially improving performance.

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