我编写了以下代码来检查System.arraycopy和克隆函数的行为。我希望这些函数返回数组的副本,但它们所做的只是返回对原始数组的引用,这在程序的后面部分中很明显,其中我更改了原始值。副本不应更改,但它也会更改。请帮助为什么其以这种方式运行?

public class Testing {

    public static int a[][] = new int[2][2];

    public static void setValueOfA() {
        a[0][0] = 1;
        a[0][1] = 1;
        a[1][0] = 1;
        a[1][1] = 1;
    }

    public static int[][] getValueOfA() {
        int[][] t = new int[2][2];

// Case 1: Not working
//        t = (int[][]) a.clone();
// Case 2: Not working
//        System.arraycopy(a, 0, t, 0, 2);
// Case 3: Working
        for (int i = 0; i < 2; i++) {
            for (int j = 0; j < 2; j++) {
                t[i][j] = a[i][j];
            }
        }
        return t;
    }

    public static void main(String[] args) {
        int[][] temp;

        setValueOfA();
        temp = getValueOfA();
        System.out.println("Value of a");
        for (int i = 0; i < 2; i++) {
            for (int j = 0; j < 2; j++) {
                System.out.print(a[i][j] + " ");
            }
            System.out.println();
        }
        System.out.println("Value of temp");
        for (int i = 0; i < 2; i++) {
            for (int j = 0; j < 2; j++) {
                System.out.print(temp[i][j] + " ");
            }
            System.out.println();
        }

        a[0][0] = 2; a[0][1] = 2; a[1][0] = 2; a[1][1] = 2;

        System.out.println("Value of a");
        for (int i = 0; i < 2; i++) {
            for (int j = 0; j < 2; j++) {
                System.out.print(a[i][j] + " ");
            }
            System.out.println();
        }
        System.out.println("Value of temp");
        for (int i = 0; i < 2; i++) {
            for (int j = 0; j < 2; j++) {
                System.out.print(temp[i][j] + " ");
            }
            System.out.println();
        }
    }
}

最佳答案

我相信(尚未测试过)System.arraycopy可以将源数组复制到目标数组。

您对System.arraycopy的调用等效于:

t[0] = a[0];
t[1] = a[1];


由于a[0]a[1]本身是数组,因此,如果以后更改a[i][j],也将更改t[i][j](因为a[i]t[i]引用相同的数组)。

关于java - 为什么System.arraycopy()函数没有创建副本,而是返回对同一数组的引用?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/27901257/

10-14 18:52
查看更多