Win a copy of Testing JavaScript Applications this week in the HTML Pages with CSS and JavaScript forum!
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Bear Bibeault
  • Ron McLeod
  • Jeanne Boyarsky
  • Paul Clapham
Sheriffs:
  • Tim Cooke
  • Liutauras Vilda
  • Junilu Lacar
Saloon Keepers:
  • Tim Moores
  • Stephan van Hulst
  • Tim Holloway
  • fred rosenberger
  • salvin francis
Bartenders:
  • Piet Souris
  • Frits Walraven
  • Carey Brown

Avoid making a copy reference of an object

 
Ranch Hand
Posts: 110
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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?
 
Ranch Hand
Posts: 148
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
Ranch Hand
Posts: 457
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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,
 
With a little knowledge, a cast iron skillet is non-stick and lasts a lifetime.
    Bookmark Topic Watch Topic
  • New Topic