This week's book giveaway is in the Servlets forum.
We're giving away four copies of Murach's Java Servlets and JSP and have Joel Murach on-line!
See this thread for details.
The moose likes Beginning Java and the fly likes Avoid making a copy reference of an object Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of Murach's Java Servlets and JSP this week in the Servlets forum!
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "Avoid making a copy reference of an object" Watch "Avoid making a copy reference of an object" New topic
Author

Avoid making a copy reference of an object

Sverre Moe
Ranch Hand

Joined: Jul 10, 2007
Posts: 110
What is the best way to copy an object?
Using obj2 = obj1 would change the values in obj1 when I change them in obj2.

I do not want the second object to be a reference to the first object. Changes in object2 should not change object1.

Is the interface Cloneable the best way to do this?
Bill Cruise
Ranch Hand

Joined: Jun 01, 2007
Posts: 148
You can make a copy constructor so that your code becomes

obj2 = new MyObject(obj1);

You then just implement the MyObject(MyObject o) constructor to perform the copy in whatever way is appropriate for your class.
Bill Shirley
Ranch Hand

Joined: Nov 08, 2007
Posts: 457
there's a 100 answers to "which way is best", and the only correct ones include "it depends"

there's a lot written about it, you should be able to find by searching a bit,

in the mean time, the copy constructor above is a minimally invasive way to get a copy,


Bill Shirley - bshirley - frazerbilt.com
if (Posts < 30) you.read( JavaRanchFAQ);
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: Avoid making a copy reference of an object
 
Similar Threads
one question about gc?
Dan's GC Question Doubt
passing parameters to a method.
Khalid: GC ?
Khalid & Rasmussen 's gc stuff.....