深度复制二维对象阵列



在我的项目中,我操作一个由对象组成的多维数组。在操作之后,我想"重置"数组。我在这里和网络上测试了几十个"深度复制"代码,但似乎没有人能使用多维数组。我使用Java 7。你能提供一个提示吗?

我所说的重置是指操作前的初始状态。因此,我想创建一个阵列备份,稍后再进行恢复。

我认为这应该可以完成所讨论数组的深度复制。

private static class CloneableObject
        implements
            Cloneable {
    @Override
    public CloneableObject clone() {
        return new CloneableObject();
    }
}

CloneableObject[][] original;

void someMethod() {
    CloneableObject[][] copy = Arrays.copyOf(this.original, this.original.length);
    for (int i = 0; i < copy.length; i++) {
        copy[i] = Arrays.copyOf(copy[i], copy[i].length);
        for (int j = 0; j < copy[i].length; j++) {
            copy[i][j] = copy[i][j].clone();
        }
    }
    /*
     * Manipulation of this.original is to be done here
     * None of the manipulations will be reflected in copy
     * 
     * Note that (this.original[n][m] == copy[n][m]) will evaluate to false,
     * where n and m are arbitrary indices of the array.
     */
    this.original = copy; // "reset"
}

如果希望不复制Object的实例,只需删除内部循环即可。

最新更新