English 中文(简体)
创建一个深度复制方法,Java
原标题:Creating a deep copy method, Java

我想做一个深度复制的方法。前几天我在这里寻求了关于这个问题的帮助,但那是针对复制构造函数的。现在我需要一个常规的方法。我已经创建了代码(不工作),但我只是不完全理解它。

public GhostList deepCopy(){
        int length=this.getLength();
        GhostList jadeed=new GhostList();
        Ghost[] data = new Ghost[length];
        for (int i=0;i<this.getLength();i++){
            data[i] = new Ghost();
            data[i].setX(this.ghosts[i].getX());
            data[i].setY(this.ghosts[i].getY());
            data[i].setColor(this.ghosts[i].getColor());
            data[i].setDirection(this.ghosts[i].getDirection());
        }

        return jadeed;
    }

现在,当我创建一个名为jaded的新GhostList,然后在此基础上创建一个新的GhostData数组时,它知道数据属于jaded GhostList吗?我看不出这两者是怎么联系在一起的,尽管它们应该是。

此外,我没有得到与副本和这个对象匹配的长度。我的问题是什么?

最佳回答

You created a new GhostList and a new Ghost array.
You fill in the Ghost array and return the GhostList but the returned GhostList has nothing to do with the Ghost array.
You should add all the new ghosts to the GhostList

问题回答

首先,您提到了一个复制构造函数。如果你已经有了工作,那么在deepCopy方法中你需要做的就是:

return new GhostList(this);

让我们暂时忘记这一点,回到您发布的代码上来。您正在创建一个名为data的数组,但从未在任何地方使用过它。难道你不应该把这个数组分配给厌倦了的吗?类似于:

jadeed.ghosts = data;

最后,与其调用方法deepCopy,不如调用它克隆并实现Cloneable接口。这样做可以让每个人都知道如何使用标准接口获得对象的副本。

GhostList类将引用Ghost的数组作为其数据成员。您还没有向我们展示类定义,所以假设该成员名为foo。现在,您所需要做的就是使新创建的jaded对象的foo引用引用您创建并填充的>Ghost的数组。你可以这样做:

jadeed.foo = data;

在您返回之前,已厌倦

如果GhostList及其组成的所有内容都是Serializable,则可以将GhostList实例序列化为字节数组并重新读取。这是几行代码,除非您使用`JakartaCommonsLang-一行代码:

http://commons.apache.org/lang/api-2.5/org/apache/commons/lang/SerializationUtils.html#clone%28java.io.Serializable%29





相关问题
Spring Properties File

Hi have this j2ee web application developed using spring framework. I have a problem with rendering mnessages in nihongo characters from the properties file. I tried converting the file to ascii using ...

Logging a global ID in multiple components

I have a system which contains multiple applications connected together using JMS and Spring Integration. Messages get sent along a chain of applications. [App A] -> [App B] -> [App C] We set a ...

Java Library Size

If I m given two Java Libraries in Jar format, 1 having no bells and whistles, and the other having lots of them that will mostly go unused.... my question is: How will the larger, mostly unused ...

How to get the Array Class for a given Class in Java?

I have a Class variable that holds a certain type and I need to get a variable that holds the corresponding array class. The best I could come up with is this: Class arrayOfFooClass = java.lang....

SQLite , Derby vs file system

I m working on a Java desktop application that reads and writes from/to different files. I think a better solution would be to replace the file system by a SQLite database. How hard is it to migrate ...