【问题标题】:Why System.arraycopy() function is not creating copy but returning reference to the same array?为什么 System.arraycopy() 函数不创建副本而是返回对同一数组的引用?
【发布时间】:2015-03-10 04:13:39
【问题描述】:

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

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 不创建任何内容,也不返回任何引用(即void)。

标签: java clone arrays


【解决方案1】:

我相信(尚未测试)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] 指的是同一个数组)。

【讨论】:

    【解决方案2】:

    MUN,

    您应该使用Arrays.copyOf() 函数。看一个例子:

    http://www.tutorialspoint.com/java/util/arrays_copyof_int.htm

    /N.

    【讨论】:

      【解决方案3】:

      Arrays.copyOf 隐式使用 System.arraycopy ,它只做浅拷贝。

      要进行深度复制,请使用传统的迭代和分配方式。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2020-07-14
        • 2018-08-08
        • 2011-10-06
        • 1970-01-01
        • 2010-09-13
        • 2016-07-30
        • 2022-10-24
        相关资源
        最近更新 更多