How do I copy an object in Java?

Posted by Veera on Stack Overflow See other posts from Stack Overflow or by Veera
Published on 2009-05-15T14:30:26Z Indexed on 2010/05/17 9:30 UTC
Read the original article Hit count: 242

Filed under:
|
|
|

Consider the 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' but it should print 'foo'

So, I want to copy the 'dum' to dumtwo' and I want to change 'dum' without affecting the 'dumtwo'. But the above code is not doing that. When I change something in 'dum', the same change is happening in 'dumtwo' also.

I guess, when I say dumtwo = dum, Java copies the reference only. So, is there any way to create a fresh copy of 'dum' and assign it to 'dumtwo' ?

© Stack Overflow or respective owner

Related posts about java

Related posts about copy