LoginSignup
1
1

More than 3 years have passed since last update.

Apex 開発:deepCloneとCloneの区別

Last updated at Posted at 2020-05-19

普通の方(clone)

Account a = new Account(Name='Acme', BillingCity='New York');           

Account b = new Account();          
Account[] q1 = new Account[]{a,b};          

Account[] q2 = q1.clone();          
q1[0].BillingCity = 'San Francisco';            

System.debug(q1[0].BillingCity);            //  San Francisco
System.debug(q2[0].BillingCity);            //  San Francisco

同じポインターのため、q1修正すると、q2の値も変更されるとのことです。

deepCloneの方

Account a = new Account(Name='Acme', BillingCity='New York');                   

Account b = new Account();                  
Account[] q1 = new Account[]{a,b};                  

Account[] q2 = q1.deepClone();                  
q1[0].BillingCity = 'San Francisco';                    

System.debug(q1[0].BillingCity);            //  San Francisco       
System.debug(q2[0].BillingCity);            //  New York        
List<Account> accts = [SELECT CreatedById, CreatedDate, LastModifiedById,                   
                       LastModifiedDate, BillingCity                    
                       FROM Account                     
                       WHERE Name='Acme' OR Name='Salesforce'];                 

// Clone list while preserving timestamp and user ID fields.                    
Account[] q3 = accts.clone();                   

// Verify timestamp fields are preserved for the first list element.                    

System.debug(q3[0].Id);                 
System.debug(q3[0].CreatedById);                    
System.debug(q3[0].CreatedDate);                    
System.debug(q3[0].LastModifiedById);                   
System.debug(q3[0].LastModifiedDate);                   

image.png

List<Account> accts = [SELECT CreatedById, CreatedDate, LastModifiedById,                   
                       LastModifiedDate, BillingCity                    
                       FROM Account                     
                       WHERE Name='Acme' OR Name='Salesforce'];                 

// Clone list while preserving timestamp and user ID fields.                    
Account[] q3 = accts.deepClone(false,false,false);                  

// Verify timestamp fields are preserved for the first list element.                    

System.debug(q3[0].Id);                 
System.debug(q3[0].CreatedById);                    
System.debug(q3[0].CreatedDate);                    
System.debug(q3[0].LastModifiedById);                   
System.debug(q3[0].LastModifiedDate);                   

image.png

「Id」、参照のみ「タイムスタンプ」と「自動採番」はこまめに扱いできる。
ディフォルト:false

1
1
1

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
1