Pregunta

Let's say I have the following classes:

public class MyClass1{

   MyClass2 obj1;
   MyClass3 obj2;

}

public class MyClass2{

   MyClass4 obj;//May or may not be referencing the same MyClass4 object in MyClass3.

}

public class MyClass3{

   MyClass4 obj;//May or may not be referencing the same MyClass4 object in MyClass2.

}

How can I create a copy constructor for MyClass1 that will preserve this entire hierarchy, even if the objects in MyClass2 and MyClass3 are referencing the same object. If the above example was all I had to make work, I could do something like:

public MyClass1(MyClass1 mc1){
   if(mc1.obj1.obj == mc1.obj2.obj)
      ...
      ...
   else
      ...
      ...
}

But I'm ultimately try to copy a graph with a dozen or more nodes, a couple dozen edges, and several linked lists each of which has multiple pointers to various nodes in the list (may or may not point to the same node). Given how big and interconnected my graph is I doubt I could make the above if-else structure work.

Thanks in advance.

¿Fue útil?

Solución

One way of deep copying an object graph is by using serialization-deserialization

ByteArrayOutputStream bos = new ByteArrayOutputStream();
ObjectOutputStream out = new ObjectOutputStream(bos);
out.writeObject(topClass);

ByteArrayInputStream bis = new ByteArrayInputStream(bos.toByteArray());
ObjectInputStream in = new ObjectInputStream(bis);
MyClass1 copy = (MyClass1) in.readObject();

To do this all the classes must implement Serializable. The serialization mechanism ensures that if two references reference the same instance in the original, they will also reference the same (new) instance in the new one.

The drawbacks are:

  1. They have to implement Serializable
  2. They all have to be contained in one object. If two objects directly or indirectly reference the same instance, then the result of deep copying those two separately will produce two separate instances of the referred object.

Otros consejos

You could have a flag inside of every object indicating if the object was visited or not. This might help you: http://java.dzone.com/articles/design-patterns-visitor

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top