Deep copy of Java object

I'm trying to clone a MyGraph object, and I want it to be a deep copy, so the clowns inside the object are also cloned. Right 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 returns an error when trying to clone an arraist. I am not sure if this is the right way to add arraialists to an object.

+5
source share
4 answers

The operation clonein ArrayListreturns a shallow copy of the object and is not suitable for your purposes. Manual Workaround:

  • Create a list of target arrays of the same size as the source list
  • Iterate the source list and create a clone of each of its items in the goal list

, , , clone, , , clone . , . , Java , . Java: / SO . , :

() , :

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");
    }
}

, Java / , . .

, Dozer . Orika , :

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

, , , .

deepCopy . , , , /.

+3

, clone() on, Cloneable. , MyGraph Cloneable. Object.clone() CloneNotSupportedException.

0

cloning , , Cloneable, clone().

Copy Constructor or Serialization. , . , :)

0

Java (, ) , List<String> :

  • , , - - ( , , ). , , , .

  • , , , , . , , . , , , .

  • . , . , , , .

  • , , , . , , , .

  • , , , . , , , , , .

The specific type of object to which the field contains a link may distinguish some of the above cases, but it cannot distinguish them among all. In particular, the first and fourth scenarios require different behavior on the part of the cloning method, despite the fact that in both scenarios the link could point to ArrayList<string>.

0
source

All Articles