Win a copy of Re-engineering Legacy Software this week in the Refactoring forum
or Docker in Action in the Cloud/Virtualization forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

clone() method and copyConstructors

 
Justin Allen
Greenhorn
Posts: 18
Chrome Eclipse IDE Linux
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hello all, I work on a mid sized java project currently and we are currently using seralization to copy most of our java objects. This process bothers me because for some of our bigger objects serialization takes forever! So I've been reading about using clone() and/or copy constructors. Here is an example object in our system:



now I know this class would have to implement Cloneable interface for us to use clone but my question is since we have other objects(List of values) in this object I would have to explicitly handle them in the clone method for them to be copied correctly?

so something like this:



My second question is about copy Constructors, I have read in Josh Bloch's book Effective Java that a copy constructor something like this:


but my question is would this, how would the implementation be, would it be this:


Thanks for the help everyone.
 
Seetharaman Venkatasamy
Ranch Hand
Posts: 5575
Eclipse IDE Java Windows XP
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
you are depending on Object's clone method. so, rule is that first you implements Cloneable ... we will see the defects later dude
 
Matthew Brown
Bartender
Posts: 4565
8
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Justin Allen wrote:My second question is about copy Constructors...
...how would the implementation be, would it be this:

It depends on what you want. That gives you a shallow copy, which can be dangerous. It means that values is referencing the same list as is referenced by the original object. If you make any changes to that list then both objects will see the change.

You can make a deeper copy by copying the list - ArrayList has its own copy constructor, so you can use that:
Now values is referencing a copy of the list, so you can change them independently. But the Objects within the list are still the same Objects. For a deep copy you'd have to go through each of those and copy them as well. Whether that's necessary depends on what the objects are and how youre using them.
 
Campbell Ritchie
Sheriff
Posts: 48448
56
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Look in Joshua Bloch’s book Effective Java™; you can probably find a sample chapter of the old edition with the clone method if you search this forum. Try here first.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic