2

Say I have a java object like (just as a simple example)

 class Town{
     Public String name;
     Public Set<Business> Businesses;
     Public Set<Person> people; 
     Public Set<House> houses; 

     //... 
 }

Houses, person, business etc being complex objects which in turn have their own objects, which have their own objects etc - some with composition and some with aggregation type relationships.

Now, I need to add a clone method to the Town class, and I have two questions:

  • How do I clone thehouses Set? Do I just implement House.clone() and call houses.clone(). Will set call the clone method of each of it's members?

  • Assuming this was a non-trivial problem (houses 'has' 10 sets of aggregated complex objects, and each of them 'has' 10 sets of aggregated complex objects and so on), is there a better way to implement the clone method for Town?

Or do I just have to spend the time implementing 100 .clone() methods on sub objects, and sub-sub-objects etc? (Would that be more or less work than implementing serialize on all the sub objects and doing it that way?)

Alex
  • 21,273
  • 10
  • 61
  • 73
Paul
  • 3,318
  • 8
  • 36
  • 60
  • See also [Deep clone utility recomendation](http://stackoverflow.com/questions/665860/deep-clone-utility-recomendation) – Nivas Jun 26 '14 at 13:40
  • Check this lib from Apache: http://commons.apache.org/proper/commons-beanutils/apidocs/org/apache/commons/beanutils/BeanUtils.html#cloneBean(java.lang.Object) – Carlos Verdes Jun 26 '14 at 13:52

1 Answers1

1

You have a couple of options:

  1. Implement the clone method on all of the classes which deep copy the class and all of its instance variables (this is sometimes important to do if you do not want to rely on 3rd party frameworks)
  2. Serialize the object (it could be to a text file or a string). You can do this by using the Oracle framework Serializable that has one instance var which decodes information about the object. More info here: http://docs.oracle.com/javase/tutorial/jndi/objects/serial.html
  3. Here is a 3rd Party Library that can do a deep copy of an object: https://github.com/DozerMapper/dozer

More information on Deep Copy libraries: Java deep copy library

Community
  • 1
  • 1
Jake Chasan
  • 6,290
  • 9
  • 44
  • 90
  • 3
    4. Create a copy constructor. (Also, read Joshua Bloch's comments on clone http://www.artima.com/intv/bloch13.html) – bcorso Jun 26 '14 at 14:20