File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
The moose likes Java in General and the fly likes a distinct copy of an Object Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Java in General
Bookmark "a distinct copy of an Object" Watch "a distinct copy of an Object" New topic

a distinct copy of an Object

Robert Kennedy
Ranch Hand

Joined: Jun 27, 2008
Posts: 63
i have an object which contains values which are of type File, boolean, String, int.
I wish to make a distinct copy.
Is there a way to code this dynamically.
For all elements in objectOriginal:
objectCopy = objectOriginal(i)

or must I hard code (and maintain) the copy to reflect the actual object
objectCopy.file = objectOrigianl.file

satishkumar janakiraman
Ranch Hand

Joined: May 03, 2004
Posts: 334
What about clone? Clone will help you create a duplicate of the original object.
Norm Radder
Ranch Hand

Joined: Aug 10, 2005
Posts: 692
I think you have to override the clone method to do deep copying.
Read the API Object.clone() method doc for more details.
Robert Kennedy
Ranch Hand

Joined: Jun 27, 2008
Posts: 63
I have read that the clone method is somewhat unreliable (at least for objects).

For the present I will create a copy method in the class.

Campbell Ritchie

Joined: Oct 13, 2005
Posts: 46349
Agree with Norm Radder. That is the Java way to do it, even though the clone() method may be conceptually flawed.

Do a search for sample chapters of Joshua Bloch "Effective Java." There is a sample chapter somewhere on the Sun website, but I can't remember where. That sample chapter covers the clone() method.
I agree. Here's the link:
subject: a distinct copy of an Object
It's not a secret anymore!