How to copy objects from Java

Asked 2 years ago, Updated 2 years ago, 126 views

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

2022-09-21 17:37

1 Answers

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, Reference Study this.


2022-09-21 17:37

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.