This week's book giveaway is in the OCPJP forum. We're giving away four copies of OCA/OCP Java SE 7 Programmer I & II Study Guide and have Kathy Sierra & Bert Bates on-line! See this thread for details.
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:
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.