Monday, 26 December 2016

It's always shallow copy :)

Hi Awesome Folks,

All of us are aware of the clone method of the sobject class.

I got a requirement to clone the object of the class. I thought the clone will be deep copy but to my surprise its always shallow copy.

public class Demo
{
 
    List<Account> lstAcc;

    public Demo(){
        lstAcc = new List<Account>();
        lstAcc.add(new Account(Name='Ajay'));
    }
 
    public void doclone(){
 
      system.debug('>>>>>>>>this'+this.lstAcc[0]);
   
      Demo objClone = this.clone();
      system.debug('>>>>>>>>clone'+objClone);
 
      objClone.lstAcc [0].Name = 'Vijay';
      system.debug('>>>>>>>>this.clone'+objClone.lstAcc[0]);
      system.debug('>>>>>>>>this'+this.lstAcc[0]);
    }
}

Output :
>>>>>>>>thisAccount:{Name=Ajay}

>>>>>>>>cloneDemo:[lstAcc=(Account:{Name=Ajay})]

>>>>>>>>this.cloneAccount:{Name=Vijay}

>>>>>>>>thisAccount:{Name=Vijay}


From output you can see change in the clone object modifying the main object also.

Keep Coding !!!!