如何在java中正确复制对象?

Emb*_*101 1 java arrays multidimensional-array

我一直在这个小项目,我花了20个小时解决(没有运气或结果)代码中的一个主要问题.现在,我发现真正的问题是copy()函数不能正常工作.

我究竟做错了什么?

这是我对特定问题所做的例子:

package cloneobject;

import java.util.Arrays;

public class CloneObject {

    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) {
        // TODO code application logic here
        clone(new int[3][3]);
    }

    public static void clone(int[][] x) {
        int[][] y = (int[][]) x.clone();
        System.out.println("x=");
        PrintFieldImage(x);
        System.out.println("y=");
        PrintFieldImage(y);
        x[1][1] = 3;        
        System.out.println("x=");
        PrintFieldImage(x);
        System.out.println("y=");
        PrintFieldImage(y);
        y[2][2] = 4;
        System.out.println("x=");
        PrintFieldImage(x);
        System.out.println("y=");
        PrintFieldImage(y);
    }

    public static void PrintFieldImage(int[][] field) {
        if (field != null) {
            int x;
            for (x = 0; x < field.length; x++) {
                System.out.println(Arrays.toString(field[x]));
            }
        } else {
            System.out.println("no field!");
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

这就是结果:

run:
x=
[0, 0, 0]
[0, 0, 0]
[0, 0, 0]
y=
[0, 0, 0]
[0, 0, 0]
[0, 0, 0]
x=
[0, 0, 0]
[0, 3, 0]
[0, 0, 0]
y=
[0, 0, 0]
[0, 3, 0]
[0, 0, 0]
x=
[0, 0, 0]
[0, 3, 0]
[0, 0, 4]
y=
[0, 0, 0]
[0, 3, 0]
[0, 0, 4]
BUILD SUCCESSFUL (total time: 0 seconds)
Run Code Online (Sandbox Code Playgroud)

现在我希望让x包含3,y包含4.

Plz帮忙!

mik*_*ery 7

clone()只做一个浅层克隆.您正在克隆2D数组; 数组数组.只克隆顶级数组.如果你想做一个深度克隆,你将不得不使用ol'fashioned forloop(s).

int[][] y = new int[x.length][];
for(int i=0; i<x.length; i++) {
    y[i] = x[i].clone();
}
Run Code Online (Sandbox Code Playgroud)

另请参阅在java中复制二维数组