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'
In the above code, dum
is copied to dumtwo
. Also, when changing the value of dum
, I hope it doesn't affect dumtwo
. But in the code above, if I change dum
, dumtwo
changes the same.
All I want is to copy the value, but I think DumTwo = dum points to the same object as Dum. Can't we just copy the string value from the dumtwo = dum statement?
java object copy
class DummyBean {
private String dummy;
public DummyBean(DummyBean another) {
this.dummy = another.dummy; // Copy String
}
}
Please make a copy generator like this. Another way is clone method, which would be easier.
If you want to use a clone,
© 2024 OneMinuteCode. All rights reserved.