How do I copy an object in Java? -


consider below code:

dummybean dum = new dummybean(); dum.setdummy("foo"); system.out.println(dum.getdummy()); // prints 'foo'  dummybean dumtwo = dum; system.out.println(dumtwo.getdummy()); // prints 'foo'  dum.setdummy("bar"); system.out.println(dumtwo.getdummy()); // prints 'bar' should print 'foo' 

so, want copy 'dum' 'dumtwo' , want change 'dum' without affecting 'dumtwo'. above code not doing that. when change in 'dum', same change happening in 'dumtwo' also.

i guess, when dumtwo = dum, java copies reference only. so, there way create fresh copy of 'dum' , assign 'dumtwo'?

create copy constructor:

class dummybean {   private string dummy;    public dummybean(dummybean another) {     this.dummy = another.dummy; // can access     } } 

every object has clone method can used copy object, don't use it. it's way easy create class , improper clone method. if going that, read @ least joshua bloch has in effective java.


Comments

Popular posts from this blog

commonjs - How to write a typescript definition file for a node module that exports a function? -

openid - Okta: Failed to get authorization code through API call -

thorough guide for profiling racket code -