Deep copy of Java object

I am trying to clone an object of mygraph. I hope it is a deep copy, so the ArrayLists in the object are also cloned Now I have:

public static MyGraph deepCopy(MyGraph G){
    MyGraph Copy = (MyGraph) G.clone();

    Copy.VertexG = (ArrayList<Integer>) G.VertexG.clone();
    Copy.EdgeG = (ArrayList<String>) G.EdgeG.clone();

    return Copy;
}

This will return an error when trying to clone ArrayList I'm not sure if this is the right way to add ArrayLists to objects

Solution

The clone operation in ArrayList returns a shallow copy of the object, which is not suitable for your purpose The manual solution is:

>Create a target array list of the same size as the source list > iterate over the source list and create a clone of each of its items into the target list

Obviously, this only works if the array list contains items that implement clone. In addition, the item clone operation actually returns a deep copy In other words, it cannot guarantee In fact, it is not easy to implement deep cloning for Java objects. Please refer to a lot of discussions in Java: recommended solution for deep cloning / copying an instance and other so threads for available options In addition to the answers provided there, there are other options:

serialize

If all (required) objects in the hierarchy can be serialized, you can use this simple code for deep cloning:

public MyGraph deepcopy() {
    try {
        final ByteArrayOutputStream baos = new ByteArrayOutputStream(256);
        final ObjectOutputStream oos = new ObjectOutputStream(baos);
        oos.writeObject(this);
        oos.close();

        final ObjectInputStream ois = new ObjectInputStream(
                new ByteArrayInputStream(baos.toByteArray()));
        final MyGraph clone = (QuicksortTest) ois.readObject();
        return clone;
    } catch (final Exception e) {
        throw new RuntimeException("cloning Failed");
    }
}

Note that some deep clone libraries combine standard Java serialization with reflection hacking and / or bytecode detection to make the entire object hierarchy fully serializable You may or may not need it

Copy tool

Dozer, for example, provides fast deep replication Orika can achieve the same effect, although there are more configurations:

public MyGraph deepcopy() {
    final DozerBeanMapper mapper = new DozerBeanMapper();
    final QuicksortTest clone = mapper.map(this,MyGraph.class);
    return clone;
}

The only drawback, of course, is that you need to enter additional dependencies on the project

On the total tangent, your deepcopy method should not be static In addition, you should seriously consider encapsulating the state of an object by making it private and implementing getters / setters

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>