In Java, how can I replicate an object?
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?