Page 1 of 1

In Java, how can I replicate an object?

Posted: Fri Jan 20, 2023 5:48 am
by KalamyQ

Look at the following code:

Code: Select all

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'd want to copy dum to dumtwo and alter dum without impacting dumtwo. However, the code above does not do this. When I make a modification in dum, the same thing happens in dumtwo.

When I say dumtwo = dum, Java apparently merely duplicates the reference. Is it possible to make a new duplicate of dum and assign it to dumtwo?


Re: In Java, how can I replicate an object?

Posted: Fri Jan 20, 2023 12:16 pm
by sfein1000

Most objects have a clone method. That will create a copy instead ig copying the reference. The problem is, a lot depends on how clone is implemented. Some clones are shallow and some are deep. What that means is if the object contains other objects, those object may be copied by reference (shallow) or they may be cloned themselves (deep). Unfortunately, there isn't a standard on deep vs shallow.

But for the main object, clone should do what you want.


Re: In Java, how can I replicate an object?

Posted: Mon Jan 23, 2023 3:58 pm
by KalamyQ

thanks you for your help