0

I am trying the following code where I want to make a deep copy of main object and make changes in the new created object person1. But the change get reflected in both the object. So as result main object should remain same and new created object's state should be null. And also synchronized blocks are used.

class Person {    
    public void persist() {
        print(this.toString()); //print whole object 
        Person person1 = new Person ();
        person1.setName(this.getName());
        person1.setAddress(this.getAddress());
        for(Address address : person1.getAddress()) {
            address.setState(null);
        }
        print(person1.toString()); //printobject with state as null
        print(this.toString());  // print object with state as null(ERROR)
    }
}
Vikash Jangra
  • 113
  • 2
  • 9
  • 1
    Please post the complete `Person` / `Address` class, see [mcve] (smells like `static`) –  Sep 09 '16 at 05:11
  • You're not making a deep copy - a deep copy goes all the way, not just one level. You also need to deep-copy `address` – Erwin Bolwidt Sep 09 '16 at 05:43

2 Answers2

0

What you are providing in person1.setAddress(this.getAddress()); is the address of current address in new object you need to copy the data if you want a deep copy

eg

Person p1=new Person();
List<Address> addList;
for(Address add:this.getAddress())
{
addList.add(new Address(add.getstreet,add.getHome,null/*this is state*/));
}

p1.setAddress(addList);

After you have copied only your data not object reference u can try to change the address the main object will not change or you can use Clone Method

eg: How to make a deep copy of Java ArrayList

Community
  • 1
  • 1
  • Thnx ..You saved my life.Yes the issue was that i was doing deep copy at one level.I used your way and it worked fine.Thnx a lot.. – Vikash Jangra Sep 09 '16 at 06:13
0

As you've not posted your complete code, i assume signature of methods as void Person.setName(Address add) and Address Person.getName()

what i suspect is when you are calling setName method by passing reference of Address of this Person, your setName method's implementation is just copying reference of passed Address to Person1's Address.
In case of deep copy you should not copy reference as now both this Person and Person1 points to same Address and any changes made to Address will now reflect in both the Person object.
You can avoid this by first cloning Address object(say adrs_new) in the implementation of setName and assign this adrs_new to Person1's Address instead of passed Address.

Community
  • 1
  • 1
Deepankar Singh
  • 662
  • 1
  • 9
  • 20