In Java, how can I replicate an object?

For discussions about programming, and for programming questions and advice


Moderator: Forum moderators

Post Reply
KalamyQ
Posts: 16
Joined: Wed Jul 13, 2022 10:59 am
Has thanked: 3 times

In Java, how can I replicate an object?

Post 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?

sfein1000
Posts: 96
Joined: Fri Mar 25, 2022 1:38 am
Been thanked: 4 times

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

Post 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.

KalamyQ
Posts: 16
Joined: Wed Jul 13, 2022 10:59 am
Has thanked: 3 times

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

Post by KalamyQ »

thanks you for your help

Post Reply

Return to “Programming”